package com.zatech.cgnci.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zatech.cgnci.project.base.context.UserContext;
import com.zatech.cgnci.project.base.enums.*;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.base.utils.*;
import com.zatech.cgnci.project.dto.*;
import com.zatech.cgnci.project.entity.*;
import com.zatech.cgnci.project.mapper.CgnciApprovalInfoMapper;
import com.zatech.cgnci.project.mapper.CgnciApprovalRecordMapper;
import com.zatech.cgnci.project.mapper.CgnciBusinessInsuranceMapper;
import com.zatech.cgnci.project.service.*;
import com.zatech.cgnci.project.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * <p>
 * 承保保单表 服务实现类
 * </p>
 *
 * @author Generator
 * @since 2024-12-20
 */
@Slf4j
@Service
public class CgnciBusinessInsuranceServiceImpl extends ServiceImpl<CgnciBusinessInsuranceMapper, CgnciBusinessInsuranceDO> implements CgnciBusinessInsuranceService {

    @Resource
    private CgnciBusinessProjectService cgnciBusinessProjectService;
    @Resource
    private CgnciCodeTypeService cgnciCodeTypeService;
    @Resource
    private CgnciDirectInsuranceService cgnciDirectInsuranceService;
    @Resource
    private CgnciDirectInsuranceRiskService cgnciDirectInsuranceRiskService;
    @Resource
    private CgnciDirectInsuranceDetailService cgnciDirectInsuranceDetailService;
    @Resource
    private CgnciReinsuranceInfoService cgnciReinsuranceInfoService;
    @Resource
    private CgnciReinsuranceRiskService cgnciReinsuranceRiskService;
    @Resource
    private CgnciReinsuranceRiskInsuredService cgnciReinsuranceRiskInsuredService;
    @Resource
    private CgnciReinsuranceRiskLayerService cgnciReinsuranceRiskLayerService;
    @Resource
    private CgnciUnderwritingPolicyService cgnciUnderwritingPolicyService;
    @Resource
    private CgnciAccessoryService cgnciAccessoryService;
    @Resource
    private CgnciOperationLogsService cgnciOperationLogsService;
    @Resource
    IApprovalService approvalService;
    @Resource
    CgnciApprovalRecordService approvalRecordService;
    @Resource
    CgnciApprovalInfoMapper approvalInfoMapper;
    @Resource
    CgnciApprovalRecordMapper approvalRecordMapper;
    @Resource
    CgnciReinsurerService reinsurerService;
    @Resource
    CgnciPaymentScheduleService paymentScheduleService;
    @Resource
    CgnciBillInfoService billInfoService;
    @Resource
    CgnciExchangeRateService exchangeRateService;
    @Resource
    CgnciClaimBasisService claimBasisService;
    @Resource
    CgnciAccidentLimitService accidentLimitService;
    @Resource
    CgnciSpecialConditionService specialConditionService;
    @Resource
    CgnciAccessoryService accessoryService;
    @Resource
    private CgnciEndorsementDetailService endorsementDetailService;
    @Resource
    private CgnciReinsurancePremiumBillService premiumBillService;
    @Resource
    private CgnciEndorsementService endorsementService;
    @Resource
    private CgnciClaimCaseService claimCaseService;
    @Resource
    private CgnciBusinessStatService cgnciBusinessStatService;

    @Override
    public List<CgnciBusinessInsurancePageVO> listBusinessInsurance(CgnciBusinessInsuranceQueryDTO queryDTO) {
        return this.baseMapper.listBusinessInsurance(queryDTO);
    }

    @Override
    public IPage<CgnciBusinessInsurancePageVO> pageBusinessInsurance(CgnciBusinessInsuranceQueryDTO queryDTO) {
        return this.baseMapper.pageBusinessInsurance(queryDTO.toPage(), queryDTO);
    }

    @Override
    public CgnciBusinessInsuranceMainVO detail(Long insuranceId, String type) {
        CgnciBusinessInsuranceMainVO businessInsuranceMainVO = new CgnciBusinessInsuranceMainVO();
        // 基本信息
        CgnciBusinessInsuranceDO businessInsuranceDO = this.baseMapper.selectById(insuranceId);
        if (VerifyUtils.isEmpty(businessInsuranceDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }
        CgnciBusinessInsuranceVO businessInsuranceVO = ConvertUtils.convert(businessInsuranceDO, CgnciBusinessInsuranceVO.class);
        businessInsuranceMainVO.setBusinessInsuranceVO(businessInsuranceVO);

        // 任务流程和镜像数据1对1
        CgnciApprovalInfoDO approvalInfoDO = approvalInfoMapper.selectOne(new LambdaQueryWrapper<CgnciApprovalInfoDO>().eq(CgnciApprovalInfoDO::getFormId, businessInsuranceDO.getInsuranceId()).eq(CgnciApprovalInfoDO::getFormNo, businessInsuranceDO.getFormNo()));
        if (VerifyUtils.isNotEmpty(approvalInfoDO)) {
            businessInsuranceMainVO.setApprovalInfoId(approvalInfoDO.getApprovalInfoId());
            businessInsuranceMainVO.setTaskId(approvalInfoDO.getTaskId());
            businessInsuranceMainVO.setTaskType(approvalInfoDO.getTaskType());
        }

        // 文件信息
        businessInsuranceMainVO.setAccessoryVOList(cgnciAccessoryService.listAccessoryListByBusinessId(insuranceId));

        // 承保统计字段列表
        businessInsuranceMainVO.setStatVOList(cgnciBusinessStatService.listBusinessStatBusinessId(insuranceId));

        switch (type) {
            // 保单
            case "1":
                // 直保信息
                CompletableFuture<Void> directFuture1 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setDirectInsuranceVO(cgnciDirectInsuranceService.getDirectInsuranceByBusinessId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 分入信息
                CompletableFuture<Void> divideInFuture1 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setDivideInVO(cgnciReinsuranceInfoService.getDivideInReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 超净自留处理方式
                CompletableFuture<Void> policyFuture1 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setUnderwritingPolicyVO(cgnciUnderwritingPolicyService.listUnderwritingPolicyByBusinessId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 临分分出信息
                CompletableFuture<Void> lfDivideOutFuture1 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setLfDivideOutVO(cgnciReinsuranceInfoService.getLfDivideOutReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 合约分出信息
                CompletableFuture<Void> hyDivideOutFuture1 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setHyDivideOutVOList(cgnciReinsuranceInfoService.listHyDivideOutReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                CompletableFuture.allOf(directFuture1, divideInFuture1, policyFuture1, lfDivideOutFuture1, hyDivideOutFuture1).join();
                break;
            // 分入
            case "2":
                // 直保信息
                CompletableFuture<Void> directFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setDirectInsuranceVO(cgnciDirectInsuranceService.getDirectInsuranceByBusinessId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 分入信息
                CompletableFuture<Void> divideInFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setDivideInVO(cgnciReinsuranceInfoService.getDivideInReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 超净自留处理方式
                CompletableFuture<Void> policyFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setUnderwritingPolicyVO(cgnciUnderwritingPolicyService.listUnderwritingPolicyByBusinessId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 临分分出信息
                CompletableFuture<Void> lfDivideOutFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setLfDivideOutVO(cgnciReinsuranceInfoService.getLfDivideOutReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 合约分出信息
                CompletableFuture<Void> hyDivideOutFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setHyDivideOutVOList(cgnciReinsuranceInfoService.listHyDivideOutReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 理赔条件
                CompletableFuture<Void> claimBasisFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setClaimBasisVOList(claimBasisService.listClaimBasisByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 事故限额
                CompletableFuture<Void> accidentLimitFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setAccidentLimitVOList(accidentLimitService.listAccidentLimitByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 特约条件 除外条件
                CompletableFuture<Void> conditionFuture2 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setSpecialConditionVO(specialConditionService.getSpecialCondition(insuranceId, "1"));
                    businessInsuranceMainVO.setExclusionConditionVO(specialConditionService.getSpecialCondition(insuranceId, "2"));
                }, ThreadPoolUtils.getThreadPoolExecutor());
                CompletableFuture.allOf(directFuture2, divideInFuture2, policyFuture2, lfDivideOutFuture2, hyDivideOutFuture2,
                        claimBasisFuture2, accidentLimitFuture2, conditionFuture2).join();
                break;
            // 分出
            case "3":
                // 合约分出信息
                CompletableFuture<Void> hyDivideOutFuture3 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setHyDivideOutVOList(cgnciReinsuranceInfoService.listHyDivideOutReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 费用/账单相关
                CompletableFuture<Void> billInfoFuture3 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setBillInfoVO(billInfoService.getBillInfoByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 币种
                CompletableFuture<Void> exchangeRateFuture3 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setExchangeRateVOList(exchangeRateService.listExchangeRateByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 理赔条件 事故限额
                CompletableFuture<Void> claimLimitFuture3 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setClaimBasisVOList(claimBasisService.listClaimBasisByInsuranceId(insuranceId));
                    businessInsuranceMainVO.setAccidentLimitVOList(accidentLimitService.listAccidentLimitByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());


                // 特约条件 除外条件
                CompletableFuture<Void> conditionFuture3 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setSpecialConditionVO(specialConditionService.getSpecialCondition(insuranceId, "1"));
                    businessInsuranceMainVO.setExclusionConditionVO(specialConditionService.getSpecialCondition(insuranceId, "2"));
                }, ThreadPoolUtils.getThreadPoolExecutor());
                CompletableFuture.allOf(hyDivideOutFuture3, billInfoFuture3, exchangeRateFuture3, claimLimitFuture3, conditionFuture3).join();
                break;
            // 理赔
            case "4":
                CompletableFuture<Void> divideInFuture4 = CompletableFuture.runAsync(() -> {
                    // 直保信息
                    businessInsuranceMainVO.setDirectInsuranceVO(cgnciDirectInsuranceService.getDirectInsuranceByBusinessId(insuranceId));

                    // 分入信息
                    businessInsuranceMainVO.setDivideInVO(cgnciReinsuranceInfoService.getDivideInReinsuranceByInsuranceId(insuranceId));

                    // 再保分出人
                    if (VerifyUtils.isNotEmpty(businessInsuranceMainVO.getDivideInVO())) {
                        businessInsuranceMainVO.setReinsurers(getReinsurers(businessInsuranceMainVO.getDivideInVO().getReinsurers()));
                    }

                    // 临分分出信息
                    businessInsuranceMainVO.setLfDivideOutVO(cgnciReinsuranceInfoService.getLfDivideOutReinsuranceByInsuranceId(insuranceId));

                    // 是否转分(是-true,否-false)
                    businessInsuranceMainVO.setIsDivideOut(VerifyUtils.isNotEmpty(businessInsuranceMainVO.getLfDivideOutVO()) && VerifyUtils.isNotEmpty(businessInsuranceMainVO.getLfDivideOutVO().getReinsurers()));

                    // 再保接受人
                    if (VerifyUtils.isNotEmpty(businessInsuranceMainVO.getDivideInVO())) {
                        businessInsuranceMainVO.setAcceptCompany(getReinsurers(businessInsuranceMainVO.getLfDivideOutVO().getReinsurers()));
                    }

                    // 净自留份额
                    // businessInsuranceMainVO.setRetentionAmount(this.getRetentionAmount(businessInsuranceMainVO.getDivideInVO(), businessInsuranceMainVO.getDirectInsuranceVO()));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 超净自留处理方式
                CompletableFuture<Void> policyFuture4 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setUnderwritingPolicyVO(cgnciUnderwritingPolicyService.listUnderwritingPolicyByBusinessId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 合约分出信息
                CompletableFuture<Void> hyDivideOutFuture4 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setHyDivideOutVOList(cgnciReinsuranceInfoService.listHyDivideOutReinsuranceByInsuranceId(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());

                // 是否存在批改流程
                CompletableFuture<Void> isEndorsementFuture4 = CompletableFuture.runAsync(() -> {
                    businessInsuranceMainVO.setIsEndorsement(endorsementService.isEndorsement(insuranceId));
                }, ThreadPoolUtils.getThreadPoolExecutor());
                CompletableFuture.allOf(divideInFuture4, policyFuture4, hyDivideOutFuture4, isEndorsementFuture4).join();
                break;
            default:
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }
        return businessInsuranceMainVO;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public CgnciBusinessInsuranceDO saveOrUpdateBusinessInsurance(CgnciBusinessInsuranceSaveOrUpdateDTO updateDTO, String type) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();

        // 校验项目id
        CgnciBusinessInsuranceDO checkInsurance = this.getById(updateDTO.getBusinessInsuranceUpdateDTO().getInsuranceId());
        if (VerifyUtils.isEmpty(checkInsurance)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "insuranceId有误");
        }
        // 校验状态
        if (!"0".equals(checkInsurance.getStatus()) && !"2".equals(checkInsurance.getStatus()) && !"5".equals(checkInsurance.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "当前状态不能录入");
        }

        // 提交审核校验数据
        if (VerifyUtils.isNotEmpty(updateDTO.getFlowTaskType()) && "submit".equals(updateDTO.getFlowTaskType())) {
            switch (type) {
                case "1":
                    validationByInsurance(checkInsurance, updateDTO);
                    break;
                case "2":
                    validationByDivideIn(checkInsurance, updateDTO);
                    break;
                case "3":
                    validationByDivideOut(checkInsurance, updateDTO);
                    break;
                default:
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
            }
        }

        CgnciBusinessInsuranceDO cgnciBusinessInsuranceDO = ConvertUtils.convert(updateDTO.getBusinessInsuranceUpdateDTO(), CgnciBusinessInsuranceDO.class);
        cgnciBusinessInsuranceDO.setUpdateUser(user.getNameAndCode());
        this.saveOrUpdate(cgnciBusinessInsuranceDO);

        // 直保信息
        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciDirectInsuranceUpdateDTO directInsuranceDTO = updateDTO.getDirectInsuranceDTO();
        if (VerifyUtils.isNotEmpty(directInsuranceDTO)) {
            CgnciDirectInsuranceDO directInsuranceDO = ConvertUtils.convert(directInsuranceDTO, CgnciDirectInsuranceDO.class);
            directInsuranceDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
            directInsuranceDO.setCreateUser(user.getNameAndCode());
            directInsuranceDO.setUpdateUser(user.getNameAndCode());
            cgnciDirectInsuranceService.saveOrUpdate(directInsuranceDO);

            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciDirectInsuranceRiskUpdateDTO> directRisks = directInsuranceDTO.getDirectRisks();
            if (VerifyUtils.isNotEmpty(directRisks)) {
                directRisks.forEach(risk -> {
                    // 直保险种信息
                    CgnciDirectInsuranceRiskDO directRiskDO = ConvertUtils.convert(risk, CgnciDirectInsuranceRiskDO.class);
                    directRiskDO.setDirectInsuranceId(directInsuranceDO.getDirectId());
                    directRiskDO.setCreateUser(user.getNameAndCode());
                    directRiskDO.setUpdateUser(user.getNameAndCode());
                    cgnciDirectInsuranceRiskService.saveOrUpdate(directRiskDO);

                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciDirectInsuranceDetailUpdateDTO> details = risk.getDetails();
                    if (VerifyUtils.isNotEmpty(details)) {
                        details.forEach(riskDetail -> {
                            CgnciDirectInsuranceDetailDO detail = ConvertUtils.convert(riskDetail, CgnciDirectInsuranceDetailDO.class);
                            detail.setDirectId(directRiskDO.getRiskId());
                            detail.setCreateUser(user.getNameAndCode());
                            detail.setUpdateUser(user.getNameAndCode());
                            cgnciDirectInsuranceDetailService.saveOrUpdate(detail);

                            // 免赔文件
                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO> accessoryDTOList = riskDetail.getAccessoryDTOList();
                            if (VerifyUtils.isNotEmpty(accessoryDTOList)) {
                                List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
                                accessoryDTOList.forEach(accessory -> {
                                    CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                                    // 文件绑定业务数据
                                    accessoryDO.setBusinessId(detail.getDetailId());
                                    accessoryList.add(accessoryDO);
                                });
                                accessoryService.saveOrUpdateBatch(accessoryList);
                            }
                        });
                    }
                });
            }
        }

        // 分入信息
        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO divideInDTO = updateDTO.getDivideInDTO();
        if (VerifyUtils.isNotEmpty(divideInDTO)) {
            CgnciReinsuranceInfoDO divideInDO = ConvertUtils.convert(divideInDTO, CgnciReinsuranceInfoDO.class);
            divideInDO.setReinsuranceType("1");
            divideInDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
            divideInDO.setCreateUser(user.getNameAndCode());
            divideInDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.saveOrUpdate(divideInDO);

            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> reinsuranceRisks = divideInDTO.getRisks();
            if (VerifyUtils.isNotEmpty(reinsuranceRisks)) {
                reinsuranceRisks.forEach(risk -> {
                    // 分入险种信息
                    CgnciReinsuranceRiskDO reinsuranceRiskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    reinsuranceRiskDO.setReinsuranceId(divideInDO.getReinsuranceId());
                    reinsuranceRiskDO.setCreateUser(user.getNameAndCode());
                    reinsuranceRiskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.saveOrUpdate(reinsuranceRiskDO);

                    // 分人险种标的
                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO> riskInsureds = risk.getRiskInsureds();
                    if (VerifyUtils.isNotEmpty(riskInsureds)) {
                        riskInsureds.forEach(riskInsured -> {
                            // 分人险种标的信息
                            CgnciReinsuranceRiskInsuredDO reinsuranceRiskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                            reinsuranceRiskInsuredDO.setReinsuranceRiskId(reinsuranceRiskDO.getReinsuranceRiskId());
                            reinsuranceRiskInsuredDO.setCreateUser(user.getNameAndCode());
                            reinsuranceRiskInsuredDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskInsuredService.saveOrUpdate(reinsuranceRiskInsuredDO);

                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO> riskLayers = riskInsured.getRiskLayers();
                            if (VerifyUtils.isNotEmpty(riskLayers)) {
                                riskLayers.forEach(riskLayerDTO -> {
                                    CgnciReinsuranceRiskLayerDO riskLayer = ConvertUtils.convert(riskLayerDTO, CgnciReinsuranceRiskLayerDO.class);
                                    riskLayer.setReinsuranceRiskId(reinsuranceRiskInsuredDO.getRiskInsuredId());
                                    riskLayer.setCreateUser(user.getNameAndCode());
                                    riskLayer.setUpdateUser(user.getNameAndCode());
                                    cgnciReinsuranceRiskLayerService.saveOrUpdate(riskLayer);

                                    // 免赔文件
                                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO> accessoryDTOList = riskLayerDTO.getAccessoryDTOList();
                                    if (VerifyUtils.isNotEmpty(accessoryDTOList)) {
                                        List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
                                        accessoryDTOList.forEach(accessory -> {
                                            CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                                            // 文件绑定业务数据
                                            accessoryDO.setBusinessId(riskLayer.getLayerId());
                                            accessoryList.add(accessoryDO);
                                        });
                                        accessoryService.saveOrUpdateBatch(accessoryList);
                                    }
                                });
                            }
                        });
                    }

                });
            }

            // 方案信息list
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerUpdateDTO> reinsurers = divideInDTO.getReinsurers();
            if (VerifyUtils.isNotEmpty(reinsurers)) {
                reinsurers.forEach(reinsurer -> {
                    // 方案信息
                    CgnciReinsurerDO reinsurerDO = ConvertUtils.convert(reinsurer, CgnciReinsurerDO.class);
                    reinsurerDO.setReinsuranceId(divideInDO.getReinsuranceId());
                    reinsurerDO.setCreateUser(user.getNameAndCode());
                    reinsurerDO.setUpdateUser(user.getNameAndCode());
                    reinsurerService.saveOrUpdate(reinsurerDO);

                    // 保存文件关联
                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO> accessoryDTO = reinsurer.getAccessoryDTO();
                    if (VerifyUtils.isNotEmpty(accessoryDTO)) {
                        List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
                        accessoryDTO.forEach(accessory -> {
                            CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                            // 文件绑定业务数据
                            accessoryDO.setBusinessId(reinsurerDO.getReinsurerId());
                            accessoryList.add(accessoryDO);
                        });
                        accessoryService.saveOrUpdateBatch(accessoryList);
                    }

                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskUpdateDTO> reinsurerRisks = reinsurer.getRisks();
                    if (VerifyUtils.isNotEmpty(reinsurerRisks)) {
                        reinsurerRisks.forEach(risk -> {
                            // 分入险种信息
                            CgnciReinsuranceRiskDO reinsuranceRiskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                            reinsuranceRiskDO.setReinsuranceId(reinsurerDO.getReinsurerId());
                            reinsuranceRiskDO.setCreateUser(VerifyUtils.isEmpty(reinsuranceRiskDO.getCreateUser()) ? user.getNameAndCode() : reinsuranceRiskDO.getCreateUser());
                            reinsuranceRiskDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskService.saveOrUpdate(reinsuranceRiskDO);

                            // 分人险种标的
                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskInsuredUpdateDTO> riskInsureds = risk.getRiskInsureds();
                            if (VerifyUtils.isNotEmpty(riskInsureds)) {
                                riskInsureds.forEach(riskInsured -> {
                                    // 分人险种标的信息
                                    CgnciReinsuranceRiskInsuredDO reinsuranceRiskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                                    reinsuranceRiskInsuredDO.setReinsuranceRiskId(reinsuranceRiskDO.getReinsuranceRiskId());
                                    reinsuranceRiskInsuredDO.setCreateUser(VerifyUtils.isEmpty(reinsuranceRiskInsuredDO.getCreateUser()) ? user.getNameAndCode() : reinsuranceRiskInsuredDO.getCreateUser());
                                    reinsuranceRiskInsuredDO.setUpdateUser(user.getNameAndCode());
                                    cgnciReinsuranceRiskInsuredService.saveOrUpdate(reinsuranceRiskInsuredDO);

                                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskLayerUpdateDTO> riskLayers = riskInsured.getRiskLayers();
                                    if (VerifyUtils.isNotEmpty(riskLayers)) {
                                        riskLayers.forEach(riskLayerDTO -> {
                                            CgnciReinsuranceRiskLayerDO riskLayer = ConvertUtils.convert(riskLayerDTO, CgnciReinsuranceRiskLayerDO.class);
                                            riskLayer.setReinsuranceRiskId(reinsuranceRiskInsuredDO.getRiskInsuredId());
                                            riskLayer.setCreateUser(user.getNameAndCode());
                                            riskLayer.setUpdateUser(user.getNameAndCode());
                                            cgnciReinsuranceRiskLayerService.saveOrUpdate(riskLayer);

                                            // 免赔文件
                                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO> accessoryDTOList = riskLayerDTO.getAccessoryDTOList();
                                            if (VerifyUtils.isNotEmpty(accessoryDTOList)) {
                                                List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
                                                accessoryDTOList.forEach(accessory -> {
                                                    CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                                                    // 文件绑定业务数据
                                                    accessoryDO.setBusinessId(riskLayer.getLayerId());
                                                    accessoryList.add(accessoryDO);
                                                });
                                                accessoryService.saveOrUpdateBatch(accessoryList);
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
        }


        // 超净自留处理方式
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciUnderwritingPolicyUpdateDTO> underwritingPolicyDTO = updateDTO.getUnderwritingPolicyDTO();
        if (VerifyUtils.isNotEmpty(underwritingPolicyDTO)) {
            List<CgnciUnderwritingPolicyDO> underwritingPolicyDOList = ConvertUtils.convert(underwritingPolicyDTO, CgnciUnderwritingPolicyDO.class);
            underwritingPolicyDOList.forEach(policy -> {
                policy.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
                policy.setCreateUser(user.getNameAndCode());
                policy.setUpdateUser(user.getNameAndCode());
            });
            cgnciUnderwritingPolicyService.saveOrUpdateBatch(underwritingPolicyDOList);
        }

        // 临分分出信息
        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO lfDivideOutDTO = updateDTO.getLfDivideOutDTO();
        if (VerifyUtils.isNotEmpty(lfDivideOutDTO)) {
            CgnciReinsuranceInfoDO lfDivideOutDO = ConvertUtils.convert(lfDivideOutDTO, CgnciReinsuranceInfoDO.class);
            lfDivideOutDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
            lfDivideOutDO.setReinsuranceType("3");
            lfDivideOutDO.setCreateUser(user.getNameAndCode());
            lfDivideOutDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.saveOrUpdate(lfDivideOutDO);
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> reinsuranceRisks = lfDivideOutDTO.getRisks();
            if (VerifyUtils.isNotEmpty(reinsuranceRisks)) {
                reinsuranceRisks.forEach(risk -> {
                    // 分入险种信息
                    CgnciReinsuranceRiskDO reinsuranceRiskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    reinsuranceRiskDO.setReinsuranceId(lfDivideOutDO.getReinsuranceId());
                    reinsuranceRiskDO.setCreateUser(user.getNameAndCode());
                    reinsuranceRiskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.saveOrUpdate(reinsuranceRiskDO);

                    // 临分分出险种标的
                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO> riskInsureds = risk.getRiskInsureds();
                    if (VerifyUtils.isNotEmpty(riskInsureds)) {
                        riskInsureds.forEach(riskInsured -> {
                            // 临分分出险种标的信息
                            CgnciReinsuranceRiskInsuredDO reinsuranceRiskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                            reinsuranceRiskInsuredDO.setReinsuranceRiskId(reinsuranceRiskDO.getReinsuranceRiskId());
                            reinsuranceRiskInsuredDO.setCreateUser(user.getNameAndCode());
                            reinsuranceRiskInsuredDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskInsuredService.saveOrUpdate(reinsuranceRiskInsuredDO);

                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO> riskLayers = riskInsured.getRiskLayers();
                            if (VerifyUtils.isNotEmpty(riskLayers)) {
                                List<CgnciReinsuranceRiskLayerDO> riskLayerDOList = new ArrayList<>();
                                riskLayers.forEach(layer -> {
                                    // 分入险种层信息
                                    CgnciReinsuranceRiskLayerDO reinsuranceRiskLayerDO = ConvertUtils.convert(layer, CgnciReinsuranceRiskLayerDO.class);
                                    reinsuranceRiskLayerDO.setReinsuranceRiskId(reinsuranceRiskInsuredDO.getRiskInsuredId());
                                    reinsuranceRiskLayerDO.setCreateUser(user.getNameAndCode());
                                    reinsuranceRiskLayerDO.setUpdateUser(user.getNameAndCode());
                                    riskLayerDOList.add(reinsuranceRiskLayerDO);
                                });
                                cgnciReinsuranceRiskLayerService.saveOrUpdateBatch(riskLayerDOList);
                            }
                        });
                    }

                });
            }

            // 再保人list
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerUpdateDTO> reinsurers = lfDivideOutDTO.getReinsurers();
            if (VerifyUtils.isNotEmpty(reinsurers)) {
                reinsurers.forEach(reinsurer -> {
                    // 再保人
                    CgnciReinsurerDO reinsurerDO = ConvertUtils.convert(reinsurer, CgnciReinsurerDO.class);
                    reinsurerDO.setReinsuranceId(lfDivideOutDO.getReinsuranceId());
                    reinsurerDO.setCreateUser(VerifyUtils.isEmpty(reinsurerDO.getCreateUser()) ? user.getNameAndCode() : reinsurerDO.getCreateUser());
                    reinsurerDO.setUpdateUser(user.getNameAndCode());
                    reinsurerService.saveOrUpdate(reinsurerDO);

                    // 保存文件关联
                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO> accessoryDTO = reinsurer.getAccessoryDTO();
                    if (VerifyUtils.isNotEmpty(accessoryDTO)) {
                        List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
                        accessoryDTO.forEach(accessory -> {
                            CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                            // 文件绑定业务数据
                            accessoryDO.setBusinessId(reinsurerDO.getReinsurerId());
                            accessoryList.add(accessoryDO);
                        });
                        accessoryService.saveOrUpdateBatch(accessoryList);
                    }

                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskUpdateDTO> risks = reinsurer.getRisks();
                    if (VerifyUtils.isNotEmpty(risks)) {
                        risks.forEach(risk -> {
                            // 分入险种信息
                            CgnciReinsuranceRiskDO reinsuranceRiskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                            reinsuranceRiskDO.setReinsuranceId(reinsurerDO.getReinsurerId());
                            reinsuranceRiskDO.setCreateUser(user.getNameAndCode());
                            reinsuranceRiskDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskService.saveOrUpdate(reinsuranceRiskDO);

                            // 分人险种标的
                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskInsuredUpdateDTO> riskInsureds = risk.getRiskInsureds();
                            if (VerifyUtils.isNotEmpty(riskInsureds)) {
                                riskInsureds.forEach(riskInsured -> {
                                    // 分人险种标的信息
                                    CgnciReinsuranceRiskInsuredDO reinsuranceRiskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                                    reinsuranceRiskInsuredDO.setReinsuranceRiskId(reinsuranceRiskDO.getReinsuranceRiskId());
                                    reinsuranceRiskInsuredDO.setCreateUser(user.getNameAndCode());
                                    reinsuranceRiskInsuredDO.setUpdateUser(user.getNameAndCode());
                                    cgnciReinsuranceRiskInsuredService.saveOrUpdate(reinsuranceRiskInsuredDO);

                                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskLayerUpdateDTO> riskLayers = riskInsured.getRiskLayers();
                                    if (VerifyUtils.isNotEmpty(riskLayers)) {
                                        List<CgnciReinsuranceRiskLayerDO> riskLayerDOList = ConvertUtils.convert(riskLayers, CgnciReinsuranceRiskLayerDO.class);
                                        riskLayerDOList.forEach(layer -> {
                                            // 分入险种层信息
                                            layer.setReinsuranceRiskId(reinsuranceRiskInsuredDO.getRiskInsuredId());
                                            layer.setCreateUser(user.getNameAndCode());
                                            layer.setUpdateUser(user.getNameAndCode());
                                        });
                                        cgnciReinsuranceRiskLayerService.saveOrUpdateBatch(riskLayerDOList);
                                    }
                                });
                            }
                        });
                    }


                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciPaymentScheduleUpdateDTO> payments = reinsurer.getPayments();
                    if (VerifyUtils.isNotEmpty(payments)) {
                        List<CgnciPaymentScheduleDO> paymentScheduleDOList = ConvertUtils.convert(payments, CgnciPaymentScheduleDO.class);
                        paymentScheduleDOList.forEach(payment -> {
                            // 支付计划
                            payment.setReinsuranceId(reinsurerDO.getReinsurerId());
                            payment.setCreateUser(user.getNameAndCode());
                            payment.setUpdateUser(user.getNameAndCode());
                        });
                        paymentScheduleService.saveOrUpdateBatch(paymentScheduleDOList);
                    }


                    // 保费变化量
                    CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciEndorsementDetailUpdateDTO endorsementDetailUpdateDTO = reinsurer.getEndorsementDetailUpdateDTO();
                    if (VerifyUtils.isNotEmpty(endorsementDetailUpdateDTO)) {
                        CgnciEndorsementDetailDO endorsementDetailDO = ConvertUtils.convert(endorsementDetailUpdateDTO, CgnciEndorsementDetailDO.class);
                        endorsementDetailDO.setReinsurerId(reinsurerDO.getReinsurerId());
                        endorsementDetailDO.setCreateUser(user.getNameAndCode());
                        endorsementDetailDO.setUpdateUser(user.getNameAndCode());
                        endorsementDetailService.saveOrUpdate(endorsementDetailDO);

                        // 保费变化量--缴费期次
                        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciPaymentScheduleUpdateDTO> changePayments = endorsementDetailUpdateDTO.getPayments();
                        if (VerifyUtils.isNotEmpty(changePayments)) {
                            List<CgnciPaymentScheduleDO> changePaymentScheduleDOList = ConvertUtils.convert(changePayments, CgnciPaymentScheduleDO.class);
                            changePaymentScheduleDOList.forEach(payment -> {
                                // 支付计划
                                payment.setReinsuranceId(endorsementDetailDO.getDetailId());
                                payment.setCreateUser(user.getNameAndCode());
                                payment.setUpdateUser(user.getNameAndCode());
                            });
                            paymentScheduleService.saveOrUpdateBatch(changePaymentScheduleDOList);
                        }
                    }
                });
            }
        }

        // 合约分出信息
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> hyDivideOutDTOList = updateDTO.getHyDivideOutDTOList();
        if (VerifyUtils.isNotEmpty(hyDivideOutDTOList)) {
            hyDivideOutDTOList.forEach(hyDivideOutDTO -> {
                CgnciReinsuranceInfoDO hyDivideOutDO = ConvertUtils.convert(hyDivideOutDTO, CgnciReinsuranceInfoDO.class);
                hyDivideOutDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
                hyDivideOutDO.setReinsuranceType("2");
                hyDivideOutDO.setCreateUser(VerifyUtils.isEmpty(hyDivideOutDO.getCreateUser()) ? user.getNameAndCode() : hyDivideOutDO.getCreateUser());
                hyDivideOutDO.setUpdateUser(user.getNameAndCode());
                cgnciReinsuranceInfoService.saveOrUpdate(hyDivideOutDO);

                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> reinsuranceRisks = hyDivideOutDTO.getRisks();
                if (VerifyUtils.isNotEmpty(reinsuranceRisks)) {
                    reinsuranceRisks.forEach(risk -> {
                        // 分入险种信息
                        CgnciReinsuranceRiskDO reinsuranceRiskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                        reinsuranceRiskDO.setReinsuranceId(hyDivideOutDO.getReinsuranceId());
                        reinsuranceRiskDO.setCreateUser(VerifyUtils.isEmpty(reinsuranceRiskDO.getCreateUser()) ? user.getNameAndCode() : reinsuranceRiskDO.getCreateUser());
                        reinsuranceRiskDO.setUpdateUser(user.getNameAndCode());
                        cgnciReinsuranceRiskService.saveOrUpdate(reinsuranceRiskDO);

                        // 分出险种标的
                        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO> riskInsureds = risk.getRiskInsureds();
                        if (VerifyUtils.isNotEmpty(riskInsureds)) {
                            riskInsureds.forEach(riskInsured -> {
                                // 分人险种标的信息
                                CgnciReinsuranceRiskInsuredDO reinsuranceRiskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                                reinsuranceRiskInsuredDO.setReinsuranceRiskId(reinsuranceRiskDO.getReinsuranceRiskId());
                                reinsuranceRiskInsuredDO.setCreateUser(VerifyUtils.isEmpty(reinsuranceRiskInsuredDO.getCreateUser()) ? user.getNameAndCode() : reinsuranceRiskInsuredDO.getCreateUser());
                                reinsuranceRiskInsuredDO.setUpdateUser(user.getNameAndCode());
                                cgnciReinsuranceRiskInsuredService.saveOrUpdate(reinsuranceRiskInsuredDO);

                                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO> riskLayers = riskInsured.getRiskLayers();
                                if (VerifyUtils.isNotEmpty(riskLayers)) {
                                    riskLayers.forEach(layer -> {
                                        // 分入险种层信息
                                        CgnciReinsuranceRiskLayerDO reinsuranceRiskLayerDO = ConvertUtils.convert(layer, CgnciReinsuranceRiskLayerDO.class);
                                        reinsuranceRiskLayerDO.setReinsuranceRiskId(reinsuranceRiskInsuredDO.getRiskInsuredId());
                                        reinsuranceRiskLayerDO.setCreateUser(VerifyUtils.isEmpty(reinsuranceRiskLayerDO.getCreateUser()) ? user.getNameAndCode() : reinsuranceRiskLayerDO.getCreateUser());
                                        reinsuranceRiskLayerDO.setUpdateUser(user.getNameAndCode());
                                        cgnciReinsuranceRiskLayerService.saveOrUpdate(reinsuranceRiskLayerDO);

                                        // 交易对手
                                        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciCounterpartyUpdateDTO> counterpartyDTOList = layer.getCounterpartyDTOList();
                                        List<CgnciReinsurerDO> counterpartyDOList = ConvertUtils.convert(counterpartyDTOList, CgnciReinsurerDO.class);
                                        counterpartyDOList.forEach(counterparty -> {
                                            counterparty.setReinsuranceId(reinsuranceRiskLayerDO.getLayerId());
                                            counterparty.setCreateUser(user.getNameAndCode());
                                            counterparty.setUpdateUser(user.getNameAndCode());
                                        });
                                        reinsurerService.saveOrUpdateBatch(counterpartyDOList);
                                    });
                                }
                            });
                        }
                    });
                }
            });
        }

        // 费用/账单相关
        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciBillInfoUpdateDTO billInfoDTO = updateDTO.getBillInfoDTO();
        if (VerifyUtils.isNotEmpty(billInfoDTO)) {
            CgnciBillInfoDO billInfoDO = ConvertUtils.convert(billInfoDTO, CgnciBillInfoDO.class);
            billInfoDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
            billInfoDO.setCreateUser(VerifyUtils.isEmpty(billInfoDO.getCreateUser()) ? user.getNameAndCode() : billInfoDO.getCreateUser());
            billInfoDO.setUpdateUser(user.getNameAndCode());
            billInfoService.saveOrUpdate(billInfoDO);
        }

        // 币种相关
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciExchangeRateUpdateDTO> exchangeRateDTOList = updateDTO.getExchangeRateDTOList();
        if (VerifyUtils.isNotEmpty(exchangeRateDTOList)) {
            List<CgnciExchangeRateDO> exchangeRateDOList = ConvertUtils.convert(exchangeRateDTOList, CgnciExchangeRateDO.class);
            if (VerifyUtils.isNotEmpty(exchangeRateDOList)) {
                exchangeRateDOList.forEach(rate -> {
                    rate.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
                    rate.setCreateUser(VerifyUtils.isEmpty(rate.getCreateUser()) ? user.getNameAndCode() : rate.getCreateUser());
                    rate.setUpdateUser(user.getNameAndCode());
                });
                exchangeRateService.saveOrUpdateBatch(exchangeRateDOList);
            }
        }

        // 理赔条件
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciClaimBasisUpdateDTO> claimBasisDTOList = updateDTO.getClaimBasisDTOList();
        if (VerifyUtils.isNotEmpty(claimBasisDTOList)) {
            List<CgnciClaimBasisDO> claimBasisDOList = ConvertUtils.convert(claimBasisDTOList, CgnciClaimBasisDO.class);
            if (VerifyUtils.isNotEmpty(claimBasisDOList)) {
                claimBasisDOList.forEach(claimBasis -> {
                    claimBasis.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
                    claimBasis.setCreateUser(VerifyUtils.isEmpty(claimBasis.getCreateUser()) ? user.getNameAndCode() : claimBasis.getCreateUser());
                    claimBasis.setUpdateUser(user.getNameAndCode());
                });
                claimBasisService.saveOrUpdateBatch(claimBasisDOList);
            }
        }


        // 事故限额
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciAccidentLimitUpdateDTO> accidentLimitDTOList = updateDTO.getAccidentLimitDTOList();
        if (VerifyUtils.isNotEmpty(accidentLimitDTOList)) {
            List<CgnciAccidentLimitDO> accidentLimitDOList = ConvertUtils.convert(accidentLimitDTOList, CgnciAccidentLimitDO.class);
            accidentLimitDOList.forEach(limit -> {
                limit.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
                limit.setCreateUser(VerifyUtils.isEmpty(limit.getCreateUser()) ? user.getNameAndCode() : limit.getCreateUser());
                limit.setUpdateUser(user.getNameAndCode());
            });
            accidentLimitService.saveOrUpdateBatch(accidentLimitDOList);
        }


        // 特约条件
        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciSpecialConditionUpdateDTO specialConditionDTO = updateDTO.getSpecialConditionDTO();
        if (VerifyUtils.isNotEmpty(specialConditionDTO)) {
            CgnciSpecialConditionDO specialConditionDO = ConvertUtils.convert(specialConditionDTO, CgnciSpecialConditionDO.class);
            specialConditionDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
            specialConditionDO.setConditionType("1");
            specialConditionDO.setCreateUser(VerifyUtils.isEmpty(specialConditionDO.getCreateUser()) ? user.getNameAndCode() : specialConditionDO.getCreateUser());
            specialConditionDO.setUpdateUser(user.getNameAndCode());
            specialConditionService.saveOrUpdate(specialConditionDO);
        }

        // 除外条件
        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciSpecialConditionUpdateDTO exclusionConditionDTO = updateDTO.getExclusionConditionDTO();
        if (VerifyUtils.isNotEmpty(exclusionConditionDTO)) {
            CgnciSpecialConditionDO exclusionConditionDO = ConvertUtils.convert(exclusionConditionDTO, CgnciSpecialConditionDO.class);
            exclusionConditionDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
            exclusionConditionDO.setConditionType("2");
            exclusionConditionDO.setCreateUser(VerifyUtils.isEmpty(exclusionConditionDO.getCreateUser()) ? user.getNameAndCode() : exclusionConditionDO.getCreateUser());
            exclusionConditionDO.setUpdateUser(user.getNameAndCode());
            specialConditionService.saveOrUpdate(exclusionConditionDO);
        }

        // 文件信息
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO> accessoryDTOList = updateDTO.getAccessoryDTOList();
        if (VerifyUtils.isNotEmpty(accessoryDTOList)) {
            List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
            accessoryDTOList.forEach(accessory -> {
                CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                // 文件绑定业务数据
                accessoryDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
                accessoryList.add(accessoryDO);
            });
            accessoryService.saveOrUpdateBatch(accessoryList);
        }

        // 承保统计字段list
        if (VerifyUtils.isNotEmpty(divideInDTO)) {
            List<CgnciBusinessStatDO> statDOList = new ArrayList<>();
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> divideInRisks = divideInDTO.getRisks();
            if (VerifyUtils.isNotEmpty(divideInRisks)) {
                divideInRisks.forEach(divideInRisk -> {
                    // 跟进业务id和险种代码查询统计字段
                    CgnciBusinessStatDO statDO = cgnciBusinessStatService.getOne(new LambdaQueryWrapper<CgnciBusinessStatDO>()
                            .eq(CgnciBusinessStatDO::getBusinessId, cgnciBusinessInsuranceDO.getInsuranceId())
                            .eq(CgnciBusinessStatDO::getRiskSubTypeCode, divideInRisk.getRiskSubTypeCode()));
                    if (VerifyUtils.isEmpty(statDO)) {
                        statDO = new CgnciBusinessStatDO();
                    }
                    statDO.setBusinessId(cgnciBusinessInsuranceDO.getInsuranceId());
                    statDO.setRiskClass(divideInRisk.getRiskClass());
                    statDO.setRiskClassCode(divideInRisk.getRiskClassCode());
                    statDO.setRiskSubType(divideInRisk.getRiskSubType());
                    statDO.setRiskSubTypeCode(divideInRisk.getRiskSubTypeCode());


                    // 获取当前险种所有标的的险种层信息
                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO> divideInRiskInsureds = divideInRisk.getRiskInsureds();
                    List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO> divideInRiskLayers
                            = divideInRiskInsureds.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO::getRiskLayers).flatMap(List::stream).collect(Collectors.toList());
                    BigDecimal shareRatio = BeanUtils.sumBigDecimalProperty(divideInRiskLayers, CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO::getShareRatio);
                    BigDecimal shareLimit = BeanUtils.sumBigDecimalProperty(divideInRiskLayers, CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO::getShareLimit);
                    statDO.setShareRatio(shareRatio);
                    statDO.setShareLimit(shareLimit);

                    BigDecimal cededRatio = BigDecimal.ZERO;
                    BigDecimal cededLimit = BigDecimal.ZERO;
                    if (VerifyUtils.isNotEmpty(lfDivideOutDTO)) {
                        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> divideOutRisks = lfDivideOutDTO.getRisks();
                        // 查询临分分出的险种信息,匹配分人的险种code
                        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO divideOutRisk
                                = divideOutRisks.stream().filter(value -> divideInRisk.getRiskSubTypeCode().equals(value.getRiskSubTypeCode())).findFirst().orElse(null);
                        // 获取当前险种所有标的的险种层信息
                        if (VerifyUtils.isNotEmpty(divideOutRisk)) {
                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO> divideOutRiskInsureds = divideOutRisk.getRiskInsureds();

                            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO> divideOutRiskLayers
                                    = divideOutRiskInsureds.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO::getRiskLayers).flatMap(List::stream).collect(Collectors.toList());
                            if ("1".equals(lfDivideOutDTO.getReinsuranceMethod())) {
                                cededRatio = BeanUtils.sumBigDecimalProperty(divideOutRiskLayers, CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO::getCededRatio);
                            } else if ("2".equals(lfDivideOutDTO.getReinsuranceMethod())) {
                                cededRatio = BeanUtils.sumBigDecimalProperty(divideOutRiskLayers, CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO::getLayerPremiumRatio);
                            }
                            cededLimit = BeanUtils.sumBigDecimalProperty(divideOutRiskLayers, CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO::getCededLimit);
                        }
                    }
                    statDO.setCededRatio(cededRatio);
                    statDO.setCededLimit(cededLimit);
                    statDO.setRetentionRatio(statDO.getShareRatio().subtract(statDO.getCededRatio()));
                    statDO.setRetentionLimit(statDO.getShareLimit().subtract(statDO.getCededLimit()));
                    statDO.setCreateUser(VerifyUtils.isEmpty(statDO.getCreateUser()) ? user.getNameAndCode() : statDO.getCreateUser());
                    statDO.setUpdateUser(user.getNameAndCode());
                    statDOList.add(statDO);
                });
            }
            cgnciBusinessStatService.saveOrUpdateBatch(statDOList);
        }
        return checkInsurance;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submit(FlowTaskSubmitDTO flowTaskDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        CgnciBusinessInsuranceDO businessInsuranceDO = this.getById(flowTaskDTO.getFormId());
        // 校验是否存在
        if (VerifyUtils.isEmpty(businessInsuranceDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }
        FlowTaskVO submit = approvalService.submit(flowTaskDTO);
        // 回调提交审核状态流程
        businessInsuranceDO.setStatus(submit.getStatus());
        this.updateById(businessInsuranceDO);
        //操作日志
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(businessInsuranceDO.getInsuranceId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.POLICY.getCode());
        operationLogsDTO.setOperationType(getOperationType(businessInsuranceDO.getBusinessType(), "submit"));
        operationLogsDTO.setCreator(user.getNameAndCode());
        cgnciOperationLogsService.saveLog(operationLogsDTO);
        /*ApprovalRecordVO approvalRecordVo = approvalRecordService.getPreviousApprovalRecord(businessInsuranceDO.getInsuranceId());
        String content = String.format("{%s}{%s}{%s} 流转至{%s}", BusinessStatusEnum.getDescByCode(submit.getStatus()), approvalRecordVo.getTaskType(), approvalRecordVo.getTaskId(), approvalRecordVo.getCurrentApproverAndName());
        operationLogsDTO.setContent(content);
        operationLogsDTO.setOperationType(OperationTypeEnum.TASK_TRANSFER.getCode());
        operationLogsDTO.setCreator("系统");
        cgnciOperationLogsService.saveLog(operationLogsDTO);*/
    }

    @Override
    public void approve(FlowTaskApprovalDTO flowTaskDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验是否存在
        CgnciBusinessInsuranceDO businessInsuranceDO = this.getById(flowTaskDTO.getFormId());
        if (VerifyUtils.isEmpty(businessInsuranceDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }

        FlowTaskVO approve = approvalService.approve(flowTaskDTO);
        // 回调审批通过状态流程
        businessInsuranceDO.setStatus(approve.getStatus());

        if (1 == approve.getIsEnd()) {
            businessInsuranceDO.setIsMirror("0");
            businessInsuranceDO.setIsEffective("1");

            // 审批通过之后,更新业务编号
            // 判断项目编号是否有值
            if (VerifyUtils.isEmpty(businessInsuranceDO.getBusinessNo())) {
                String businessType = businessInsuranceDO.getBusinessType();
                String businessNo;
                switch (businessType) {
                    case "1":
                        // 保单
                        businessNo = cgnciCodeTypeService.getBusinessNo("zbbdh", "number");
                        // 保单号：P+3位险种代码+4位年份数字+0001
                        businessInsuranceDO.setBusinessNo("P" + BeanUtils.getFirstValue(businessInsuranceDO.getRiskSubTypeCode()) + businessInsuranceDO.getBusinessYear() + businessNo);
                        break;
                    case "2":
                    case "3":
                        // 获取合约编号
                        String businessForm = businessInsuranceDO.getBusinessForm();
                        // T+承保年度+合约类型+0001
                        // 合约类型：比例：P；非比例：N
                        if ("1".equals(businessForm)) {
                            businessNo = cgnciCodeTypeService.getBusinessNo("hybh-bl", "number");
                            businessInsuranceDO.setBusinessNo("T" + businessInsuranceDO.getBusinessYear() + "P" + businessNo);
                        } else {
                            businessNo = cgnciCodeTypeService.getBusinessNo("hybh-fbl", "number");
                            businessInsuranceDO.setBusinessNo("T" + businessInsuranceDO.getBusinessYear() + "N" + businessNo);
                        }
                        break;
                    default:
                        throw new IllegalArgumentException("businessType参数不合法");
                }
            }


            // 审批通过之后,根据工作流配置的模块id(模块id可以有多个分组任务,比如新增任务和编辑任务)查询所有的业务数据,
            // 需要把最新审批通过的业务数据变为不是镜像数据,之前不是镜像数据的业务数据变更为镜像数据
            List<CgnciApprovalInfoDO> cgnciApprovalInfoDOS = approvalInfoMapper.selectList(new LambdaQueryWrapper<CgnciApprovalInfoDO>()
                    .eq(CgnciApprovalInfoDO::getFormNo, approve.getFormNo())
                    .eq(CgnciApprovalInfoDO::getStatus, "3")
                    .orderByDesc(CgnciApprovalInfoDO::getCreateTime).last("limit 2"));
            if (cgnciApprovalInfoDOS.size() == 2) {
                CgnciApprovalInfoDO firstApprovalInfo = cgnciApprovalInfoDOS.get(0);
                CgnciApprovalInfoDO secondApprovalInfo = cgnciApprovalInfoDOS.get(1);
                // 标记最近一条审批通过的业务数据为非镜像数据
                CgnciBusinessInsuranceDO firstBusinessInsurance = this.getById(firstApprovalInfo.getFormId());
                firstBusinessInsurance.setIsMirror("0");
                firstBusinessInsurance.setIsEffective("1");
                this.updateById(firstBusinessInsurance);

                // 标记之后的一个业务数据为镜像数据
                CgnciBusinessInsuranceDO secondBusinessInsurance = this.getById(secondApprovalInfo.getFormId());
                secondBusinessInsurance.setIsMirror("1");
                secondBusinessInsurance.setIsEffective("0");
                this.updateById(secondBusinessInsurance);
            }
        }
        this.updateById(businessInsuranceDO);


        //审批通过后记录日志
        ApprovalRecordVO approvalRecord = approvalRecordService.getPreviousApprovalRecord(businessInsuranceDO.getInsuranceId());
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(businessInsuranceDO.getInsuranceId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.POLICY.getCode());
        operationLogsDTO.setOperationType(getOperationType(businessInsuranceDO.getBusinessType(), "pass"));
        operationLogsDTO.setContent(flowTaskDTO.getApproverOpinions());
        operationLogsDTO.setCreator(user.getNameAndCode());
        cgnciOperationLogsService.saveLog(operationLogsDTO);

        /*String content = String.format("{%s}{%s}{%s} 流转至{%s}", BusinessStatusEnum.getDescByCode(approve.getStatus()), approvalRecord.getTaskType(), approvalRecord.getTaskId(), approvalRecord.getCurrentApproverAndName());
        operationLogsDTO.setContent(content);
        operationLogsDTO.setOperationType(OperationTypeEnum.TASK_TRANSFER.getCode());
        operationLogsDTO.setCreator("系统");
        cgnciOperationLogsService.saveLog(operationLogsDTO);*/
        // 保单审批通过,异步生成账单数据
        if (1 == approve.getIsEnd() && "1".equals(businessInsuranceDO.getBusinessType())) {
            log.info("保单号:{},审批通过,异步生成账单数据", businessInsuranceDO.getBusinessNo());
            ThreadPoolUtils.executor(() -> {
                premiumBillService.generateDisengagement(businessInsuranceDO.getInsuranceId());
            });
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void back(FlowTaskBackDTO flowTaskDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验续保是否存在
        CgnciBusinessInsuranceDO businessInsuranceDO = this.getById(flowTaskDTO.getFormId());
        if (VerifyUtils.isEmpty(businessInsuranceDO)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }

        FlowTaskVO back = approvalService.back(flowTaskDTO);
        // 回调审批通过状态流程
        businessInsuranceDO.setStatus(back.getStatus());
        this.updateById(businessInsuranceDO);
        //记录操作日志
        ApprovalRecordVO approvalRecord = approvalRecordService.getPreviousApprovalRecord(businessInsuranceDO.getInsuranceId());
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(businessInsuranceDO.getInsuranceId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.POLICY.getCode());
        operationLogsDTO.setOperationType(getOperationType(businessInsuranceDO.getBusinessType(), "back"));
        operationLogsDTO.setCreator(user.getNameAndCode());
        operationLogsDTO.setContent(flowTaskDTO.getApproverOpinions());
        cgnciOperationLogsService.saveLog(operationLogsDTO);
        /*String content = String.format("{%s}{%s}{%s} 流转至{%s}", BusinessStatusEnum.getDescByCode(back.getStatus()), approvalRecord.getTaskType(), approvalRecord.getTaskId(), approvalRecord.getCurrentApproverAndName());
        operationLogsDTO.setContent(content);
        operationLogsDTO.setOperationType(OperationTypeEnum.TASK_TRANSFER.getCode());
        operationLogsDTO.setCreator("系统");
        cgnciOperationLogsService.saveLog(operationLogsDTO);*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void signOut(Long insuranceId) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        CgnciBusinessInsuranceDO businessInsuranceDO = this.baseMapper.selectById(insuranceId);
        if (VerifyUtils.isEmpty(businessInsuranceDO)) {
            throw new GlobalException(ResponseCodeEnum.PARAMS_ILLEGAL, "inPlanId有误");
        }
        // 判断当前状态是否为 录入中
        if (!"0".equals(businessInsuranceDO.getStatus()) && !"2".equals(businessInsuranceDO.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "当前状态不能注销");
        }
        approvalService.cancelTask(FlowTaskCancelDTO.builder().formId(String.valueOf(businessInsuranceDO.getInsuranceId())).formNo(businessInsuranceDO.getFormNo()).build());
        // 回调提交审核状态流程
        businessInsuranceDO.setStatus("4");
        this.updateById(businessInsuranceDO);
        //注销操作日志
        CgnciOperationLogsDTO operationLogsDTO = new CgnciOperationLogsDTO();
        operationLogsDTO.setBizNo(String.valueOf(businessInsuranceDO.getInsuranceId()));
        operationLogsDTO.setBizType(BusinessScenariosEnum.POLICY.getCode());
        operationLogsDTO.setOperationType(getOperationType(businessInsuranceDO.getBusinessType(), "signOut"));
        operationLogsDTO.setCreator(user.getNameAndCode());
        cgnciOperationLogsService.saveLog(operationLogsDTO);
    }

    @Override
    public List<ApprovalRecordVO> log(Long insuranceId) {
        List<CgnciApprovalRecordDO> approvalRecordDOList = approvalRecordMapper.selectList(new LambdaQueryWrapper<CgnciApprovalRecordDO>().eq(CgnciApprovalRecordDO::getFormId, insuranceId));
        return ConvertUtils.convert(approvalRecordDOList, ApprovalRecordVO.class);
    }

    // 获取保单信息
    @Override
    public CgnciBusinessInsuranceMainVO getPolicyInfo(String policyNo) {
        if (VerifyUtils.isEmpty(policyNo)) {
            return null;
        }
        LambdaQueryWrapper<CgnciBusinessInsuranceDO> query = new LambdaQueryWrapper<CgnciBusinessInsuranceDO>().eq(CgnciBusinessInsuranceDO::getBusinessNo, policyNo).eq(CgnciBusinessInsuranceDO::getStatus, "3").eq(CgnciBusinessInsuranceDO::getIsEffective, "1").eq(CgnciBusinessInsuranceDO::getIsMirror, "0");
        CgnciBusinessInsuranceDO cgnciBusinessInsuranceDO = baseMapper.selectOne(query);
        if (VerifyUtils.isEmpty(cgnciBusinessInsuranceDO)) {
            return null;
        }
        return this.detail(cgnciBusinessInsuranceDO.getInsuranceId(), "4");
    }

    @Override
    public CgnciBusinessInsuranceClaimVO getInsuranceClaim(String policyNo, String caseNo) {
        if (VerifyUtils.isEmpty(policyNo) || VerifyUtils.isEmpty(caseNo)) {
            return null;
        }
        LambdaQueryWrapper<CgnciBusinessInsuranceDO> query = new LambdaQueryWrapper<CgnciBusinessInsuranceDO>().eq(CgnciBusinessInsuranceDO::getBusinessNo, policyNo).eq(CgnciBusinessInsuranceDO::getIsMirror, "0");
        CgnciBusinessInsuranceDO cgnciBusinessInsuranceDO = baseMapper.selectOne(query);
        if (VerifyUtils.isEmpty(cgnciBusinessInsuranceDO)) {
            return null;
        }

        CgnciClaimCaseDO claimCaseDO = claimCaseService.getOne(new LambdaQueryWrapper<CgnciClaimCaseDO>()
                .eq(CgnciClaimCaseDO::getCaseNo, caseNo));
        BigDecimal totalAmount = VerifyUtils.isEmpty(claimCaseDO.getTotalAmount()) ? BigDecimal.ZERO : claimCaseDO.getTotalAmount();

        if (!"1".equals(cgnciBusinessInsuranceDO.getIsEffective()) && !"3".equals(cgnciBusinessInsuranceDO.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "保单不是生效状态");
        }
        CgnciBusinessInsuranceClaimVO result = new CgnciBusinessInsuranceClaimVO();
        // 分入信息
        CompletableFuture<Void> divideInFuture = CompletableFuture.runAsync(() -> {
            CgnciReinsuranceInfoVO divideInVO = cgnciReinsuranceInfoService.getDivideInReinsuranceByInsuranceId(cgnciBusinessInsuranceDO.getInsuranceId());
            List<CgnciReinsurerVO> reinsurers = divideInVO.getReinsurers();
            if (VerifyUtils.isNotEmpty(reinsurers)) {
                reinsurers.forEach(reinsurer -> {
                    List<CgnciReinsurerRiskVO> risks = reinsurer.getRisks();
                    if (VerifyUtils.isNotEmpty(risks)) {
                        risks.forEach(risk -> {
                            List<CgnciReinsurerRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                            if (VerifyUtils.isNotEmpty(riskInsureds)) {
                                riskInsureds.forEach(riskInsured -> {
                                    List<CgnciReinsurerRiskLayerVO> riskLayers = riskInsured.getRiskLayers();
                                    if (VerifyUtils.isNotEmpty(riskLayers)) {
                                        riskLayers.forEach(riskLayer -> {
                                            // 分人结算--结算金额（原始币种）=(整个赔案）摊赔金额*承接比例
                                            // riskLayer.setSettlementAmountOriginal(totalAmount.multiply(riskLayer.getShareRatio()).setScale(2, RoundingMode.HALF_UP));
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
            result.setDivideInVO(divideInVO);
        }, ThreadPoolUtils.getThreadPoolExecutor());

        // 临分分出信息
        CompletableFuture<Void> lfDivideOutFuture = CompletableFuture.runAsync(() -> {
            CgnciReinsuranceInfoVO lfDivideOutVO = cgnciReinsuranceInfoService.getLfDivideOutReinsuranceByInsuranceId(cgnciBusinessInsuranceDO.getInsuranceId());
            List<CgnciReinsurerVO> reinsurers = lfDivideOutVO.getReinsurers();
            if (VerifyUtils.isNotEmpty(reinsurers)) {
                reinsurers.forEach(reinsurer -> {
                    List<CgnciReinsurerRiskVO> risks = reinsurer.getRisks();
                    if (VerifyUtils.isNotEmpty(risks)) {
                        risks.forEach(risk -> {
                            List<CgnciReinsurerRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                            if (VerifyUtils.isNotEmpty(riskInsureds)) {
                                riskInsureds.forEach(riskInsured -> {
                                    List<CgnciReinsurerRiskLayerVO> riskLayers = riskInsured.getRiskLayers();
                                    if (VerifyUtils.isNotEmpty(riskLayers)) {
                                        riskLayers.forEach(riskLayer -> {
                                            // 分出摊回--结算金额（原始币种）=(整个赔案）摊赔金额*分出比例
                                            if ("1".equals(lfDivideOutVO.getReinsuranceMethod())) {
                                                // riskLayer.setSettlementAmountOriginal(totalAmount.multiply(riskLayer.getCededRatio()).setScale(2, RoundingMode.HALF_UP));
                                            }
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
            result.setLfDivideOutVO(lfDivideOutVO);
        }, ThreadPoolUtils.getThreadPoolExecutor());
        CompletableFuture.allOf(divideInFuture, lfDivideOutFuture).join();
        return result;
    }


    @Override
    public CgnciBusinessInsuranceDO nextProjectCreate(CgnciBusinessInsuranceNextCreateDTO addCreateDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验项目id
        CgnciBusinessProjectDO copyProject = cgnciBusinessProjectService.getById(addCreateDTO.getProjectId());
        if (VerifyUtils.isEmpty(copyProject)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "请输入正确的项目编号");
        }
        if (!"1".equals(copyProject.getIsEffective()) && !"3".equals(copyProject.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该项目不是已生效的状态");
        }
        CgnciBusinessInsuranceDO businessInsuranceDO = ConvertUtils.convert(addCreateDTO, CgnciBusinessInsuranceDO.class);
        // 第一步先插入业务数据,用来绑定工作量formId formNo,并且关联工作台的跳转地址url以及参数
        businessInsuranceDO.setFormNo(BeanUtils.getUUID());
        // 业务类型-保单
        businessInsuranceDO.setBusinessType("1");
        // 险种、保单币种、汇率约定方式、汇率、业务承接类型复制外，其他均不复制
        businessInsuranceDO.setProjectNo(copyProject.getProjectNo());
        businessInsuranceDO.setProjectName(copyProject.getProjectName());
        businessInsuranceDO.setRiskClass(copyProject.getRiskClass());
        businessInsuranceDO.setRiskClassCode(copyProject.getRiskClassCode());
        businessInsuranceDO.setRiskSubType(copyProject.getRiskSubType());
        businessInsuranceDO.setRiskSubTypeCode(copyProject.getRiskSubTypeCode());
        businessInsuranceDO.setStartDate(copyProject.getStartDate());
        businessInsuranceDO.setEndDate(copyProject.getEndDate());
        businessInsuranceDO.setInsuranceDays(copyProject.getInsuranceDays());
        businessInsuranceDO.setBusinessYear(copyProject.getProjectYear());
        businessInsuranceDO.setBusinessYears(copyProject.getProjectYears());
        businessInsuranceDO.setCurrency(copyProject.getCurrency());
        businessInsuranceDO.setExchangeRate(copyProject.getExchangeRate());
        businessInsuranceDO.setExchangeRateType(copyProject.getExchangeRateType());
        businessInsuranceDO.setProjectAcceptanceType(copyProject.getProjectAcceptanceType());
        businessInsuranceDO.setCoverageScope(copyProject.getCoverageScope());
        businessInsuranceDO.setEntryDate(copyProject.getEntryDate());
        businessInsuranceDO.setPml(copyProject.getPml());
        businessInsuranceDO.setIsSurveyReport(copyProject.getIsSurveyReport());
        businessInsuranceDO.setCreateUser(user.getNameAndCode());
        businessInsuranceDO.setUpdateUser(user.getNameAndCode());
        // 基本信息
        this.save(businessInsuranceDO);

        // 获取项目信息
        CgnciBusinessProjectMainVO projectVO = cgnciBusinessProjectService.detail(addCreateDTO.getProjectId());

        // 直保信息
        CgnciDirectInsuranceVO directInsuranceVO = projectVO.getDirectInsuranceVO();
        if (VerifyUtils.isNotEmpty(directInsuranceVO)) {
            CgnciDirectInsuranceDO directInsuranceDO = ConvertUtils.convert(directInsuranceVO, CgnciDirectInsuranceDO.class);
            directInsuranceDO.setDirectId(null);
            directInsuranceDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            directInsuranceDO.setCreateUser(user.getNameAndCode());
            directInsuranceDO.setUpdateUser(user.getNameAndCode());
            cgnciDirectInsuranceService.save(directInsuranceDO);

            // 直保险种
            List<CgnciDirectInsuranceRiskVO> insuranceRisks = directInsuranceVO.getInsuranceRisks();
            if (VerifyUtils.isNotEmpty(insuranceRisks)) {
                insuranceRisks.forEach(risk -> {
                    CgnciDirectInsuranceRiskDO insuranceRiskDO = ConvertUtils.convert(risk, CgnciDirectInsuranceRiskDO.class);
                    insuranceRiskDO.setRiskId(null);
                    insuranceRiskDO.setDirectInsuranceId(directInsuranceDO.getDirectId());
                    insuranceRiskDO.setCreateUser(user.getNameAndCode());
                    insuranceRiskDO.setUpdateUser(user.getNameAndCode());
                    cgnciDirectInsuranceRiskService.save(insuranceRiskDO);

                    List<CgnciDirectInsuranceDetailVO> detailsVOList = risk.getDetails();
                    if (VerifyUtils.isNotEmpty(detailsVOList)) {
                        List<CgnciDirectInsuranceDetailDO> detailsDOList = ConvertUtils.convert(detailsVOList, CgnciDirectInsuranceDetailDO.class);
                        detailsDOList.forEach(detail -> {
                            detail.setDetailId(null);
                            detail.setDirectId(insuranceRiskDO.getRiskId());
                            detail.setCreateUser(user.getNameAndCode());
                            detail.setUpdateUser(user.getNameAndCode());
                        });
                        cgnciDirectInsuranceDetailService.saveBatch(detailsDOList);
                    }
                });
            }
        }


        // 分入信息
        CgnciReinsuranceInfoProjectVO divideInVO = projectVO.getDivideInVO();
        if (VerifyUtils.isNotEmpty(divideInVO)) {
            CgnciReinsuranceInfoDO divideInDO = ConvertUtils.convert(divideInVO, CgnciReinsuranceInfoDO.class);
            divideInDO.setReinsuranceId(null);
            divideInDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            divideInDO.setCreateUser(user.getNameAndCode());
            divideInDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.save(divideInDO);

            List<CgnciReinsuranceRiskProjectVO> divideInRiskVOList = divideInVO.getRisks();
            if (VerifyUtils.isNotEmpty(divideInRiskVOList)) {
                divideInRiskVOList.forEach(risk -> {
                    CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    riskDO.setReinsuranceRiskId(null);
                    riskDO.setReinsuranceId(divideInDO.getReinsuranceId());
                    riskDO.setCreateUser(user.getNameAndCode());
                    riskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.save(riskDO);

                    // 分人险种标的
                    List<CgnciReinsuranceRiskInsuredProjectVO> riskInsureds = risk.getRiskInsureds();
                    if (VerifyUtils.isNotEmpty(riskInsureds)) {
                        riskInsureds.forEach(riskInsured -> {
                            // 转化新增
                            CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                            riskInsuredDO.setRiskInsuredId(null);
                            riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                            riskInsuredDO.setCreateUser(user.getNameAndCode());
                            riskInsuredDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                            List<CgnciReinsuranceRiskLayerProjectVO> riskLayersVO = riskInsured.getRiskLayers();
                            if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                riskLayersDO.forEach(riskLayer -> {
                                    riskLayer.setLayerId(null);
                                    riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                    riskLayer.setCreateUser(user.getNameAndCode());
                                    riskLayer.setUpdateUser(user.getNameAndCode());
                                });
                                cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);

                            }

                        });
                    }

                });

            }

        }

        // 超净自留处理方式
        List<CgnciUnderwritingPolicyVO> underwritingPolicyVOList = projectVO.getUnderwritingPolicyVO();
        List<CgnciUnderwritingPolicyDO> underwritingPolicyDOList = ConvertUtils.convert(underwritingPolicyVOList, CgnciUnderwritingPolicyDO.class);
        underwritingPolicyDOList.forEach(policy -> {
            policy.setPolicyId(null);
            policy.setBusinessId(businessInsuranceDO.getInsuranceId());
            policy.setCreateUser(user.getNameAndCode());
            policy.setUpdateUser(user.getNameAndCode());
        });
        cgnciUnderwritingPolicyService.saveBatch(underwritingPolicyDOList);


        // 临分分出信息
        CgnciReinsuranceInfoProjectVO lfDivideOutVO = projectVO.getLfDivideOutVO();
        if (VerifyUtils.isNotEmpty(lfDivideOutVO)) {
            CgnciReinsuranceInfoDO lfDivideOuDO = ConvertUtils.convert(lfDivideOutVO, CgnciReinsuranceInfoDO.class);
            lfDivideOuDO.setReinsuranceId(null);
            lfDivideOuDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            lfDivideOuDO.setCreateUser(user.getNameAndCode());
            lfDivideOuDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.save(lfDivideOuDO);

            List<CgnciReinsuranceRiskProjectVO> lfDivideOutRiskVOList = lfDivideOutVO.getRisks();
            if (VerifyUtils.isNotEmpty(lfDivideOutRiskVOList)) {
                lfDivideOutRiskVOList.forEach(risk -> {
                    CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    riskDO.setReinsuranceRiskId(null);
                    riskDO.setReinsuranceId(lfDivideOuDO.getReinsuranceId());
                    riskDO.setCreateUser(user.getNameAndCode());
                    riskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.save(riskDO);

                    // 临分分出险种标的
                    List<CgnciReinsuranceRiskInsuredProjectVO> riskInsureds = risk.getRiskInsureds();
                    if (VerifyUtils.isNotEmpty(riskInsureds)) {
                        riskInsureds.forEach(riskInsured -> {
                            // 转化新增
                            CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                            riskInsuredDO.setRiskInsuredId(null);
                            riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                            riskInsuredDO.setCreateUser(user.getNameAndCode());
                            riskInsuredDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                            List<CgnciReinsuranceRiskLayerProjectVO> riskLayersVO = riskInsured.getRiskLayers();
                            if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                riskLayersDO.forEach(riskLayer -> {
                                    riskLayer.setLayerId(null);
                                    riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                    riskLayer.setCreateUser(user.getNameAndCode());
                                    riskLayer.setUpdateUser(user.getNameAndCode());
                                });
                                cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);

                            }
                        });

                    }

                });
            }

        }

        // 文件信息
        List<CgnciAccessoryVO> accessoryVOList = projectVO.getAccessoryVOList();
        if (VerifyUtils.isNotEmpty(accessoryVOList)) {
            List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
            accessoryVOList.forEach(accessory -> {
                CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                // 设置插入数据
                accessoryDO.setAccId(null);
                accessoryDO.setBusinessId(businessInsuranceDO.getInsuranceId());
                accessoryDO.setCreateUser(user.getNameAndCode());
                accessoryDO.setUpdateUser(user.getNameAndCode());
                accessoryList.add(accessoryDO);
            });
            accessoryService.saveBatch(accessoryList);
        }

        return businessInsuranceDO;
    }

    @Override
    public CgnciBusinessInsuranceDO nextInsuranceCreate(CgnciBusinessInsuranceNextCreateDTO addCreateDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验项目id
        CgnciBusinessProjectDO copyProject = cgnciBusinessProjectService.getById(addCreateDTO.getProjectId());
        if (VerifyUtils.isEmpty(copyProject)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "请输入正确的项目编号");
        }
        if (!"1".equals(copyProject.getIsEffective()) && !"3".equals(copyProject.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该项目不是已生效的状态，不允许复制");
        }

        // 校验原保单id
        CgnciBusinessInsuranceDO copyInsurance = this.getById(addCreateDTO.getOriginalBusinessId());
        if (VerifyUtils.isEmpty(copyInsurance)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "请输入正确的保单号");
        }
        if (!"1".equals(copyInsurance.getIsEffective()) && !"3".equals(copyInsurance.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该保单不是已生效的状态");
        }

        // 校验所选保单的险种是否匹配所选项目的险种
        boolean containsAll = containsAll(copyProject.getRiskSubTypeCode(), copyInsurance.getRiskSubTypeCode());
        if (!containsAll) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "所选保单的险种与项目的险种不匹配，无法进行续保录单");
        }

        CgnciBusinessInsuranceDO businessInsuranceDO = ConvertUtils.convert(addCreateDTO, CgnciBusinessInsuranceDO.class);
        // 第一步先插入业务数据,用来绑定工作量formId formNo,并且关联工作台的跳转地址url以及参数
        businessInsuranceDO.setFormNo(BeanUtils.getUUID());
        // 业务类型-保单
        businessInsuranceDO.setBusinessType("1");
        businessInsuranceDO.setOriginalBusinessId(copyInsurance.getInsuranceId());
        businessInsuranceDO.setOriginalBusinessNo(copyInsurance.getBusinessNo());
        businessInsuranceDO.setProjectNo(copyInsurance.getProjectNo());
        businessInsuranceDO.setProjectName(copyInsurance.getProjectName());
        businessInsuranceDO.setRiskClass(copyInsurance.getRiskClass());
        businessInsuranceDO.setRiskClassCode(copyInsurance.getRiskClassCode());
        businessInsuranceDO.setRiskSubType(copyInsurance.getRiskSubType());
        businessInsuranceDO.setRiskSubTypeCode(copyInsurance.getRiskSubTypeCode());
        businessInsuranceDO.setStartDate(copyInsurance.getStartDate());
        businessInsuranceDO.setEndDate(copyInsurance.getEndDate());
        businessInsuranceDO.setInsuranceDays(copyInsurance.getInsuranceDays());
        businessInsuranceDO.setBusinessYear(copyInsurance.getBusinessYear());
        businessInsuranceDO.setBusinessYears(copyInsurance.getBusinessYears());
        businessInsuranceDO.setCurrency(copyInsurance.getCurrency());
        businessInsuranceDO.setExchangeRate(copyInsurance.getExchangeRate());
        businessInsuranceDO.setExchangeRateType(copyInsurance.getExchangeRateType());
        businessInsuranceDO.setProjectAcceptanceType(copyInsurance.getProjectAcceptanceType());
        businessInsuranceDO.setCoverageScope(copyInsurance.getCoverageScope());
        businessInsuranceDO.setPml(copyInsurance.getPml());
        businessInsuranceDO.setIsSurveyReport(copyInsurance.getIsSurveyReport());
        businessInsuranceDO.setCreateUser(user.getNameAndCode());
        businessInsuranceDO.setUpdateUser(user.getNameAndCode());

        // 获取原保单信息
        CgnciBusinessInsuranceMainVO insuranceVO = this.detail(addCreateDTO.getOriginalBusinessId(), "1");

        // 基本信息
        this.save(businessInsuranceDO);

        // 直保信息
        CgnciDirectInsuranceVO directInsuranceVO = insuranceVO.getDirectInsuranceVO();
        if (VerifyUtils.isNotEmpty(directInsuranceVO)) {
            CgnciDirectInsuranceDO directInsuranceDO = ConvertUtils.convert(directInsuranceVO, CgnciDirectInsuranceDO.class);
            directInsuranceDO.setDirectId(null);
            directInsuranceDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            directInsuranceDO.setCreateUser(user.getNameAndCode());
            directInsuranceDO.setUpdateUser(user.getNameAndCode());
            cgnciDirectInsuranceService.save(directInsuranceDO);

            // 直保险种
            List<CgnciDirectInsuranceRiskVO> insuranceRisks = directInsuranceVO.getInsuranceRisks();
            if (VerifyUtils.isNotEmpty(insuranceRisks)) {
                insuranceRisks.forEach(risk -> {
                    CgnciDirectInsuranceRiskDO insuranceRiskDO = ConvertUtils.convert(risk, CgnciDirectInsuranceRiskDO.class);
                    insuranceRiskDO.setRiskId(null);
                    insuranceRiskDO.setDirectInsuranceId(directInsuranceDO.getDirectId());
                    insuranceRiskDO.setCreateUser(user.getNameAndCode());
                    insuranceRiskDO.setUpdateUser(user.getNameAndCode());
                    cgnciDirectInsuranceRiskService.save(insuranceRiskDO);

                    List<CgnciDirectInsuranceDetailVO> detailsVOList = risk.getDetails();
                    if (VerifyUtils.isNotEmpty(detailsVOList)) {
                        List<CgnciDirectInsuranceDetailDO> detailsDOList = ConvertUtils.convert(detailsVOList, CgnciDirectInsuranceDetailDO.class);
                        detailsDOList.forEach(detail -> {
                            detail.setDetailId(null);
                            detail.setDirectId(directInsuranceDO.getDirectId());
                            detail.setCreateUser(user.getNameAndCode());
                            detail.setUpdateUser(user.getNameAndCode());
                        });
                        cgnciDirectInsuranceDetailService.saveBatch(detailsDOList);

                    }
                });
            }

        }


        // 分入信息
        CgnciReinsuranceInfoVO divideInVO = insuranceVO.getDivideInVO();
        if (VerifyUtils.isNotEmpty(divideInVO)) {
            CgnciReinsuranceInfoDO divideInDO = ConvertUtils.convert(divideInVO, CgnciReinsuranceInfoDO.class);
            divideInDO.setReinsuranceId(null);
            divideInDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            divideInDO.setCreateUser(user.getNameAndCode());
            divideInDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.save(divideInDO);
            // 分入信息--险类信息
            List<CgnciReinsuranceRiskVO> divideInRiskVOList = divideInVO.getRisks();
            if (VerifyUtils.isNotEmpty(divideInRiskVOList)) {
                divideInRiskVOList.forEach(risk -> {
                    CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    riskDO.setReinsuranceRiskId(null);
                    riskDO.setReinsuranceId(divideInDO.getReinsuranceId());
                    riskDO.setCreateUser(user.getNameAndCode());
                    riskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.save(riskDO);

                    // 分人险种标的
                    List<CgnciReinsuranceRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                    riskInsureds.forEach(riskInsured -> {
                        // 转化新增
                        CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                        riskInsuredDO.setRiskInsuredId(null);
                        riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                        riskInsuredDO.setCreateUser(user.getNameAndCode());
                        riskInsuredDO.setUpdateUser(user.getNameAndCode());
                        cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                        List<CgnciReinsuranceRiskLayerVO> riskLayersVO = riskInsured.getRiskLayers();
                        List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                        riskLayersDO.forEach(riskLayer -> {
                            riskLayer.setLayerId(null);
                            riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                            riskLayer.setCreateUser(user.getNameAndCode());
                            riskLayer.setUpdateUser(user.getNameAndCode());
                        });
                        cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);
                    });
                });

            }
            // 分入信息--分入方案
            List<CgnciReinsurerVO> divideInReinsurers = divideInVO.getReinsurers();
            if (VerifyUtils.isNotEmpty(divideInReinsurers)) {
                divideInReinsurers.forEach(reinsurer -> {
                    CgnciReinsurerDO reinsurerDO = ConvertUtils.convert(reinsurer, CgnciReinsurerDO.class);
                    reinsurerDO.setReinsurerId(null);
                    reinsurerDO.setReinsuranceId(divideInDO.getReinsuranceId());
                    reinsurerDO.setCreateUser(user.getNameAndCode());
                    reinsurerDO.setUpdateUser(user.getNameAndCode());
                    reinsurerService.save(reinsurerDO);

                    // 保存文件关联
                    List<CgnciAccessoryVO> accessoryVOS = reinsurer.getAccessoryVO();
                    if (VerifyUtils.isNotEmpty(accessoryVOS)) {
                        List<CgnciAccessoryDO> accessoryDOS = ConvertUtils.convert(accessoryVOS, CgnciAccessoryDO.class);
                        accessoryDOS.forEach(accessoryDO -> {
                            accessoryDO.setAccId(null);
                            accessoryDO.setBusinessId(reinsurerDO.getReinsurerId());
                            accessoryDO.setCreateUser(user.getNameAndCode());
                            accessoryDO.setUpdateUser(user.getNameAndCode());
                        });
                        accessoryService.saveBatch(accessoryDOS);
                    }

                    List<CgnciReinsurerRiskVO> risks = reinsurer.getRisks();
                    if (VerifyUtils.isNotEmpty(risks)) {
                        risks.forEach(risk -> {
                            CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                            riskDO.setReinsuranceRiskId(null);
                            riskDO.setReinsuranceId(reinsurerDO.getReinsurerId());
                            riskDO.setCreateUser(user.getNameAndCode());
                            riskDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskService.save(riskDO);

                            // 分入信息--分入方案--险类信息--分入方案标的
                            List<CgnciReinsurerRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                            if (VerifyUtils.isNotEmpty(riskInsureds)) {
                                riskInsureds.forEach(riskInsured -> {
                                    CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                                    riskInsuredDO.setRiskInsuredId(null);
                                    riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                                    riskInsuredDO.setCreateUser(user.getNameAndCode());
                                    riskInsuredDO.setUpdateUser(user.getNameAndCode());
                                    cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                                    List<CgnciReinsurerRiskLayerVO> riskLayersVO = riskInsured.getRiskLayers();
                                    if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                        List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                        riskLayersDO.forEach(riskLayer -> {
                                            riskLayer.setLayerId(null);
                                            riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                            riskLayer.setCreateUser(user.getNameAndCode());
                                            riskLayer.setUpdateUser(user.getNameAndCode());
                                        });
                                        cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);

                                    }
                                });

                            }
                        });
                    }
                });

            }

        }

        // 超净自留处理方式
        List<CgnciUnderwritingPolicyVO> underwritingPolicyVOList = insuranceVO.getUnderwritingPolicyVO();
        List<CgnciUnderwritingPolicyDO> underwritingPolicyDOList = ConvertUtils.convert(underwritingPolicyVOList, CgnciUnderwritingPolicyDO.class);
        underwritingPolicyDOList.forEach(policy -> {
            policy.setPolicyId(null);
            policy.setBusinessId(businessInsuranceDO.getInsuranceId());
            policy.setCreateUser(user.getNameAndCode());
            policy.setUpdateUser(user.getNameAndCode());
        });
        cgnciUnderwritingPolicyService.saveBatch(underwritingPolicyDOList);


        // 临分分出信息
        CgnciReinsuranceInfoVO lfDivideOutVO = insuranceVO.getLfDivideOutVO();
        if (VerifyUtils.isNotEmpty(lfDivideOutVO)) {
            CgnciReinsuranceInfoDO lfDivideOuDO = ConvertUtils.convert(lfDivideOutVO, CgnciReinsuranceInfoDO.class);
            lfDivideOuDO.setReinsuranceId(null);
            lfDivideOuDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            lfDivideOuDO.setCreateUser(user.getNameAndCode());
            lfDivideOuDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.save(lfDivideOuDO);
            // 临分分出信息--险类信息
            List<CgnciReinsuranceRiskVO> lfDivideOutRiskVOList = lfDivideOutVO.getRisks();
            if (VerifyUtils.isNotEmpty(lfDivideOutRiskVOList)) {
                lfDivideOutRiskVOList.forEach(risk -> {
                    CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    riskDO.setReinsuranceRiskId(null);
                    riskDO.setReinsuranceId(lfDivideOuDO.getReinsuranceId());
                    riskDO.setCreateUser(user.getNameAndCode());
                    riskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.save(riskDO);

                    // 临分分出信息--险类信息--分入方案标的
                    List<CgnciReinsuranceRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                    if (VerifyUtils.isNotEmpty(riskInsureds)) {
                        riskInsureds.forEach(riskInsured -> {
                            CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                            riskInsuredDO.setRiskInsuredId(null);
                            riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                            riskInsuredDO.setCreateUser(user.getNameAndCode());
                            riskInsuredDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                            List<CgnciReinsuranceRiskLayerVO> riskLayersVO = riskInsured.getRiskLayers();
                            if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                riskLayersDO.forEach(riskLayer -> {
                                    riskLayer.setLayerId(null);
                                    riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                    riskLayer.setCreateUser(user.getNameAndCode());
                                    riskLayer.setUpdateUser(user.getNameAndCode());
                                });
                                cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);

                            }

                        });

                    }

                });

            }
            // 临分分出信息--再保人
            List<CgnciReinsurerVO> lfDivideOutReinsurers = lfDivideOutVO.getReinsurers();
            if (VerifyUtils.isNotEmpty(lfDivideOutReinsurers)) {
                lfDivideOutReinsurers.forEach(reinsurer -> {
                    CgnciReinsurerDO reinsurerDO = ConvertUtils.convert(reinsurer, CgnciReinsurerDO.class);
                    reinsurerDO.setReinsurerId(null);
                    reinsurerDO.setReinsuranceId(lfDivideOuDO.getReinsuranceId());
                    reinsurerDO.setCreateUser(user.getNameAndCode());
                    reinsurerDO.setUpdateUser(user.getNameAndCode());
                    reinsurerService.save(reinsurerDO);
                    List<CgnciReinsurerRiskVO> risks = reinsurer.getRisks();
                    if (VerifyUtils.isNotEmpty(risks)) {
                        risks.forEach(risk -> {
                            CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                            riskDO.setReinsuranceRiskId(null);
                            riskDO.setReinsuranceId(reinsurerDO.getReinsurerId());
                            riskDO.setCreateUser(user.getNameAndCode());
                            riskDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskService.save(riskDO);

                            // 临分分出信息--再保人--险类信息--再保人标的
                            List<CgnciReinsurerRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                            if (VerifyUtils.isNotEmpty(riskInsureds)) {
                                riskInsureds.forEach(riskInsured -> {
                                    CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                                    riskInsuredDO.setRiskInsuredId(null);
                                    riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                                    riskInsuredDO.setCreateUser(user.getNameAndCode());
                                    riskInsuredDO.setUpdateUser(user.getNameAndCode());
                                    cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                                    List<CgnciReinsurerRiskLayerVO> riskLayersVO = riskInsured.getRiskLayers();
                                    if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                        List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                        riskLayersDO.forEach(riskLayer -> {
                                            riskLayer.setLayerId(null);
                                            riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                            riskLayer.setCreateUser(user.getNameAndCode());
                                            riskLayer.setUpdateUser(user.getNameAndCode());
                                        });
                                        cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);

                                    }

                                });

                            }

                        });
                    }
                });

            }

        }

        // 合约分出
        List<CgnciReinsuranceInfoVO> hyDivideOutVOList = insuranceVO.getHyDivideOutVOList();
        if (VerifyUtils.isNotEmpty(hyDivideOutVOList)) {
            hyDivideOutVOList.forEach(hyDivideOutVO -> {
                CgnciReinsuranceInfoDO hyDivideOutDO = ConvertUtils.convert(hyDivideOutVO, CgnciReinsuranceInfoDO.class);
                hyDivideOutDO.setReinsuranceId(null);
                hyDivideOutDO.setBusinessId(businessInsuranceDO.getInsuranceId());
                hyDivideOutDO.setCreateUser(user.getNameAndCode());
                hyDivideOutDO.setUpdateUser(user.getNameAndCode());
                cgnciReinsuranceInfoService.save(hyDivideOutDO);

                List<CgnciReinsuranceRiskVO> risks = hyDivideOutVO.getRisks();
                if (VerifyUtils.isNotEmpty(risks)) {
                    risks.forEach(risk -> {
                        CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                        riskDO.setReinsuranceRiskId(null);
                        riskDO.setReinsuranceId(hyDivideOutDO.getReinsuranceId());
                        riskDO.setCreateUser(user.getNameAndCode());
                        riskDO.setUpdateUser(user.getNameAndCode());
                        cgnciReinsuranceRiskService.save(riskDO);

                        // 合约分出信息--再保人--险类信息--再保人标的
                        List<CgnciReinsuranceRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                        if (VerifyUtils.isNotEmpty(riskInsureds)) {
                            riskInsureds.forEach(riskInsured -> {
                                CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                                riskInsuredDO.setRiskInsuredId(null);
                                riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                                riskInsuredDO.setCreateUser(user.getNameAndCode());
                                riskInsuredDO.setUpdateUser(user.getNameAndCode());
                                cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                                List<CgnciReinsuranceRiskLayerVO> layers = riskInsured.getRiskLayers();
                                if (VerifyUtils.isNotEmpty(layers)) {
                                    List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(layers, CgnciReinsuranceRiskLayerDO.class);
                                    riskLayersDO.forEach(riskLayer -> {
                                        riskLayer.setLayerId(null);
                                        riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                        riskLayer.setCreateUser(user.getNameAndCode());
                                        riskLayer.setUpdateUser(user.getNameAndCode());
                                    });
                                    cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);
                                }

                            });
                        }

                    });
                }
            });
        }

        // 文件信息
        List<CgnciAccessoryVO> accessoryVOList = insuranceVO.getAccessoryVOList();
        if (VerifyUtils.isNotEmpty(accessoryVOList)) {
            List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
            accessoryVOList.forEach(accessory -> {
                CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                // 设置插入数据
                accessoryDO.setAccId(null);
                accessoryDO.setBusinessId(businessInsuranceDO.getInsuranceId());
                accessoryDO.setCreateUser(user.getNameAndCode());
                accessoryDO.setUpdateUser(user.getNameAndCode());
                accessoryList.add(accessoryDO);
            });
            accessoryService.saveBatch(accessoryList);
        }
        return businessInsuranceDO;
    }


    @Override
    public CgnciBusinessInsuranceDO nextDivideInCreate(CgnciBusinessDivideInNextCreateDTO addCreateDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 校验项目id
        CgnciBusinessProjectDO copyProject = cgnciBusinessProjectService.getById(addCreateDTO.getProjectId());
        if (VerifyUtils.isEmpty(copyProject)) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "请输入正确的项目编号");
        }
        if (!"1".equals(copyProject.getIsEffective()) && !"3".equals(copyProject.getStatus())) {
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该项目不是已生效的状态");
        }
        CgnciBusinessInsuranceDO businessInsuranceDO = ConvertUtils.convert(addCreateDTO, CgnciBusinessInsuranceDO.class);
        // 第一步先插入业务数据,用来绑定工作量formId formNo,并且关联工作台的跳转地址url以及参数
        businessInsuranceDO.setFormNo(BeanUtils.getUUID());
        // 业务类型-分入合约
        businessInsuranceDO.setBusinessType("2");
        businessInsuranceDO.setProjectNo(copyProject.getProjectNo());
        businessInsuranceDO.setProjectName(copyProject.getProjectName());
        businessInsuranceDO.setStartDate(copyProject.getStartDate());
        businessInsuranceDO.setEndDate(copyProject.getEndDate());
        businessInsuranceDO.setInsuranceDays(copyProject.getInsuranceDays());
        businessInsuranceDO.setBusinessYear(copyProject.getProjectYear());
        businessInsuranceDO.setBusinessYears(copyProject.getProjectYears());
        businessInsuranceDO.setCurrency(copyProject.getCurrency());
        businessInsuranceDO.setExchangeRate(copyProject.getExchangeRate());
        businessInsuranceDO.setExchangeRateType(copyProject.getExchangeRateType());
        businessInsuranceDO.setProjectAcceptanceType(copyProject.getProjectAcceptanceType());
        businessInsuranceDO.setCoverageScope(copyProject.getCoverageScope());
        businessInsuranceDO.setEntryDate(copyProject.getEntryDate());
        businessInsuranceDO.setPml(copyProject.getPml());
        businessInsuranceDO.setIsSurveyReport(copyProject.getIsSurveyReport());
        businessInsuranceDO.setCreateUser(user.getNameAndCode());
        businessInsuranceDO.setUpdateUser(user.getNameAndCode());
        // 基本信息
        this.save(businessInsuranceDO);

        // 获取项目信息
        CgnciBusinessProjectMainVO projectVO = cgnciBusinessProjectService.detail(addCreateDTO.getProjectId());


        // 直保信息
        CgnciDirectInsuranceVO directInsuranceVO = projectVO.getDirectInsuranceVO();
        if (VerifyUtils.isNotEmpty(directInsuranceVO)) {
            CgnciDirectInsuranceDO directInsuranceDO = ConvertUtils.convert(directInsuranceVO, CgnciDirectInsuranceDO.class);
            directInsuranceDO.setDirectId(null);
            directInsuranceDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            directInsuranceDO.setCreateUser(user.getNameAndCode());
            directInsuranceDO.setUpdateUser(user.getNameAndCode());
            cgnciDirectInsuranceService.save(directInsuranceDO);

            // 直保险种
            List<CgnciDirectInsuranceRiskVO> insuranceRisks = directInsuranceVO.getInsuranceRisks();
            if (VerifyUtils.isNotEmpty(insuranceRisks)) {
                insuranceRisks.forEach(risk -> {
                    CgnciDirectInsuranceRiskDO insuranceRiskDO = ConvertUtils.convert(risk, CgnciDirectInsuranceRiskDO.class);
                    insuranceRiskDO.setRiskId(null);
                    insuranceRiskDO.setDirectInsuranceId(directInsuranceDO.getDirectId());
                    insuranceRiskDO.setCreateUser(user.getNameAndCode());
                    insuranceRiskDO.setUpdateUser(user.getNameAndCode());
                    cgnciDirectInsuranceRiskService.save(insuranceRiskDO);

                    List<CgnciDirectInsuranceDetailVO> detailsVOList = risk.getDetails();
                    if (VerifyUtils.isNotEmpty(detailsVOList)) {
                        List<CgnciDirectInsuranceDetailDO> detailsDOList = ConvertUtils.convert(detailsVOList, CgnciDirectInsuranceDetailDO.class);
                        detailsDOList.forEach(detail -> {
                            detail.setDetailId(null);
                            detail.setDirectId(insuranceRiskDO.getRiskId());
                            detail.setCreateUser(user.getNameAndCode());
                            detail.setUpdateUser(user.getNameAndCode());
                        });
                        cgnciDirectInsuranceDetailService.saveBatch(detailsDOList);

                    }

                });
            }

        }

        // 分入信息
        CgnciReinsuranceInfoProjectVO divideInVO = projectVO.getDivideInVO();
        if (VerifyUtils.isNotEmpty(divideInVO)) {
            CgnciReinsuranceInfoDO divideInDO = ConvertUtils.convert(divideInVO, CgnciReinsuranceInfoDO.class);
            divideInDO.setReinsuranceId(null);
            divideInDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            divideInDO.setCreateUser(user.getNameAndCode());
            divideInDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.save(divideInDO);

            List<CgnciReinsuranceRiskProjectVO> divideInRiskVOList = divideInVO.getRisks();
            if (VerifyUtils.isNotEmpty(divideInRiskVOList)) {
                divideInRiskVOList.forEach(risk -> {
                    CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    riskDO.setReinsuranceRiskId(null);
                    riskDO.setReinsuranceId(divideInDO.getReinsuranceId());
                    riskDO.setCreateUser(user.getNameAndCode());
                    riskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.save(riskDO);

                    // 分入信息--分人险种标的
                    List<CgnciReinsuranceRiskInsuredProjectVO> riskInsureds = risk.getRiskInsureds();
                    if (VerifyUtils.isNotEmpty(riskInsureds)) {
                        riskInsureds.forEach(riskInsured -> {
                            CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                            riskInsuredDO.setRiskInsuredId(null);
                            riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                            riskInsuredDO.setCreateUser(user.getNameAndCode());
                            riskInsuredDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                            List<CgnciReinsuranceRiskLayerProjectVO> riskLayersVO = riskInsured.getRiskLayers();
                            if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                riskLayersDO.forEach(riskLayer -> {
                                    riskLayer.setLayerId(null);
                                    riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                    riskLayer.setCreateUser(user.getNameAndCode());
                                    riskLayer.setUpdateUser(user.getNameAndCode());
                                });
                                cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);
                            }
                        });

                    }

                });

            }

        }

        // 超净自留处理方式
        List<CgnciUnderwritingPolicyVO> underwritingPolicyVOList = projectVO.getUnderwritingPolicyVO();
        List<CgnciUnderwritingPolicyDO> underwritingPolicyDOList = ConvertUtils.convert(underwritingPolicyVOList, CgnciUnderwritingPolicyDO.class);
        underwritingPolicyDOList.forEach(policy -> {
            policy.setPolicyId(null);
            policy.setBusinessId(businessInsuranceDO.getInsuranceId());
            policy.setCreateUser(user.getNameAndCode());
            policy.setUpdateUser(user.getNameAndCode());
        });
        cgnciUnderwritingPolicyService.saveBatch(underwritingPolicyDOList);


        // 临分分出信息
        CgnciReinsuranceInfoProjectVO lfDivideOutVO = projectVO.getLfDivideOutVO();
        if (VerifyUtils.isNotEmpty(lfDivideOutVO)) {
            CgnciReinsuranceInfoDO lfDivideOuDO = ConvertUtils.convert(lfDivideOutVO, CgnciReinsuranceInfoDO.class);
            lfDivideOuDO.setReinsuranceId(null);
            lfDivideOuDO.setBusinessId(businessInsuranceDO.getInsuranceId());
            lfDivideOuDO.setCreateUser(user.getNameAndCode());
            lfDivideOuDO.setUpdateUser(user.getNameAndCode());
            cgnciReinsuranceInfoService.save(lfDivideOuDO);
            List<CgnciReinsuranceRiskProjectVO> lfDivideOutRiskVOList = lfDivideOutVO.getRisks();
            if (VerifyUtils.isNotEmpty(lfDivideOutRiskVOList)) {
                lfDivideOutRiskVOList.forEach(risk -> {
                    CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                    riskDO.setReinsuranceRiskId(null);
                    riskDO.setReinsuranceId(lfDivideOuDO.getReinsuranceId());
                    riskDO.setCreateUser(user.getNameAndCode());
                    riskDO.setUpdateUser(user.getNameAndCode());
                    cgnciReinsuranceRiskService.save(riskDO);

                    // 临分分出信息--分人险种标的
                    List<CgnciReinsuranceRiskInsuredProjectVO> riskInsureds = risk.getRiskInsureds();
                    if (VerifyUtils.isNotEmpty(riskInsureds)) {
                        riskInsureds.forEach(riskInsured -> {
                            CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                            riskInsuredDO.setRiskInsuredId(null);
                            riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                            riskInsuredDO.setCreateUser(user.getNameAndCode());
                            riskInsuredDO.setUpdateUser(user.getNameAndCode());
                            cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                            List<CgnciReinsuranceRiskLayerProjectVO> riskLayersVO = riskInsured.getRiskLayers();
                            if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                riskLayersDO.forEach(riskLayer -> {
                                    riskLayer.setLayerId(null);
                                    riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                    riskLayer.setCreateUser(user.getNameAndCode());
                                    riskLayer.setUpdateUser(user.getNameAndCode());
                                });
                                cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);
                            }

                        });

                    }

                });

            }

        }

        // 合约分出信息
        List<CgnciReinsuranceInfoProjectVO> hyDivideOutVOList = projectVO.getHyDivideOutVOList();
        if (VerifyUtils.isNotEmpty(hyDivideOutVOList)) {
            hyDivideOutVOList.forEach(hyDivideOutVO -> {
                CgnciReinsuranceInfoDO hyDivideOutDO = ConvertUtils.convert(hyDivideOutVO, CgnciReinsuranceInfoDO.class);
                hyDivideOutDO.setReinsuranceId(null);
                hyDivideOutDO.setBusinessId(businessInsuranceDO.getInsuranceId());
                hyDivideOutDO.setCreateUser(user.getNameAndCode());
                hyDivideOutDO.setUpdateUser(user.getNameAndCode());
                cgnciReinsuranceInfoService.save(hyDivideOutDO);

                List<CgnciReinsuranceRiskProjectVO> hyDivideOutRiskVOList = hyDivideOutVO.getRisks();
                if (VerifyUtils.isNotEmpty(hyDivideOutRiskVOList)) {
                    hyDivideOutRiskVOList.forEach(risk -> {
                        CgnciReinsuranceRiskDO riskDO = ConvertUtils.convert(risk, CgnciReinsuranceRiskDO.class);
                        riskDO.setReinsuranceRiskId(null);
                        riskDO.setReinsuranceId(hyDivideOutDO.getReinsuranceId());
                        riskDO.setCreateUser(user.getNameAndCode());
                        riskDO.setUpdateUser(user.getNameAndCode());
                        cgnciReinsuranceRiskService.save(riskDO);

                        // 合约分出信息--分人险种标的
                        List<CgnciReinsuranceRiskInsuredProjectVO> riskInsureds = risk.getRiskInsureds();
                        if (VerifyUtils.isNotEmpty(riskInsureds)) {
                            riskInsureds.forEach(riskInsured -> {
                                CgnciReinsuranceRiskInsuredDO riskInsuredDO = ConvertUtils.convert(riskInsured, CgnciReinsuranceRiskInsuredDO.class);
                                riskInsuredDO.setRiskInsuredId(null);
                                riskInsuredDO.setReinsuranceRiskId(riskDO.getReinsuranceRiskId());
                                riskInsuredDO.setCreateUser(user.getNameAndCode());
                                riskInsuredDO.setUpdateUser(user.getNameAndCode());
                                cgnciReinsuranceRiskInsuredService.save(riskInsuredDO);

                                List<CgnciReinsuranceRiskLayerProjectVO> riskLayersVO = riskInsured.getRiskLayers();
                                if (VerifyUtils.isNotEmpty(riskLayersVO)) {
                                    List<CgnciReinsuranceRiskLayerDO> riskLayersDO = ConvertUtils.convert(riskLayersVO, CgnciReinsuranceRiskLayerDO.class);
                                    riskLayersDO.forEach(riskLayer -> {
                                        riskLayer.setLayerId(null);
                                        riskLayer.setReinsuranceRiskId(riskInsuredDO.getRiskInsuredId());
                                        riskLayer.setCreateUser(user.getNameAndCode());
                                        riskLayer.setUpdateUser(user.getNameAndCode());
                                    });
                                    cgnciReinsuranceRiskLayerService.saveBatch(riskLayersDO);

                                }

                            });

                        }

                    });

                }
            });

        }

        // 文件信息
        List<CgnciAccessoryVO> accessoryVOList = projectVO.getAccessoryVOList();
        if (VerifyUtils.isNotEmpty(accessoryVOList)) {
            List<CgnciAccessoryDO> accessoryList = new ArrayList<>();
            accessoryVOList.forEach(accessory -> {
                CgnciAccessoryDO accessoryDO = accessoryService.getById(accessory.getAccId());
                // 设置插入数据
                accessoryDO.setAccId(null);
                accessoryDO.setBusinessId(businessInsuranceDO.getInsuranceId());
                accessoryDO.setCreateUser(user.getNameAndCode());
                accessoryDO.setUpdateUser(user.getNameAndCode());
                accessoryList.add(accessoryDO);
            });
            accessoryService.saveBatch(accessoryList);
        }

        return businessInsuranceDO;
    }

    @Override
    public BigDecimal getRetentionAmount(CgnciReinsuranceInfoVO DivideInVO, CgnciDirectInsuranceVO directInsuranceVO) {
        if (VerifyUtils.isEmpty(DivideInVO) || VerifyUtils.isEmpty(directInsuranceVO)) {
            return BigDecimal.ZERO;
        }
        // 自留额汇总,自留额可以去分人层的承接限额
        BigDecimal totalShareLimit = BigDecimal.ZERO;
        List<CgnciReinsuranceRiskVO> risks = DivideInVO.getRisks();
        if (VerifyUtils.isNotEmpty(risks)) {
            for (CgnciReinsuranceRiskVO risk : risks) {
                // 获取当前险种所有标的的险种层信息
                List<CgnciReinsuranceRiskInsuredVO> riskInsureds = risk.getRiskInsureds();
                List<CgnciReinsuranceRiskLayerVO> riskLayers =
                        riskInsureds.stream().map(CgnciReinsuranceRiskInsuredVO::getRiskLayers).flatMap(List::stream).collect(Collectors.toList());
                BigDecimal shareLimit = BeanUtils.sumBigDecimalProperty(riskLayers, CgnciReinsuranceRiskLayerVO::getShareLimit);
                totalShareLimit = totalShareLimit.add(shareLimit);
            }
        }

        // 直保保单保额汇总
        List<CgnciDirectInsuranceRiskVO> insuranceRisks = directInsuranceVO.getInsuranceRisks();
        List<CgnciDirectInsuranceDetailVO> detailVOS = insuranceRisks.stream().map(CgnciDirectInsuranceRiskVO::getDetails).flatMap(List::stream).collect(Collectors.toList());
        BigDecimal compensation = BeanUtils.sumBigDecimalProperty(detailVOS, CgnciDirectInsuranceDetailVO::getMaxCompensation);
        if (compensation.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO;
        }
        return totalShareLimit.divide(compensation, 2, RoundingMode.HALF_UP);
    }


    private String getOperationType(String businessType, String type) {
        String operationType = "";
        switch (type) {
            case "signOut":
                if ("1".equals(businessType)) {
                    operationType = OperationTypeEnum.CANCEL_ENTRY_POLICY.getCode();
                } else if ("2".equals(businessType)) {
                    operationType = OperationTypeEnum.CANCEL_REINSURANCE.getCode();
                } else {
                    operationType = OperationTypeEnum.CANCEL_OUTGOING_CONTRACT.getCode();
                }
                break;
            case "submit":
                if ("1".equals(businessType)) {
                    operationType = OperationTypeEnum.SUBMIT_ENTRY_POLICY.getCode();
                } else if ("2".equals(businessType)) {
                    operationType = OperationTypeEnum.SUBMIT_REINSURANCE.getCode();
                } else {
                    operationType = OperationTypeEnum.SUBMIT_OUTGOING_CONTRACT.getCode();
                }
                break;
            case "back":
                if ("1".equals(businessType)) {
                    operationType = OperationTypeEnum.ENTRY_POLICY_BACK.getCode();
                } else if ("2".equals(businessType)) {
                    operationType = OperationTypeEnum.REINSURANCE_AUDIT_BACK.getCode();
                } else {
                    operationType = OperationTypeEnum.OUTGOING_CONTRACT_AUDIT_BACK.getCode();
                }
                break;
            case "pass":
                if ("1".equals(businessType)) {
                    operationType = OperationTypeEnum.ENTRY_POLICY_PASS.getCode();
                } else if ("2".equals(businessType)) {
                    operationType = OperationTypeEnum.REINSURANCE_AUDIT_PASS.getCode();
                } else {
                    operationType = OperationTypeEnum.OUTGOING_CONTRACT_AUDIT_PASS.getCode();
                }
                break;
            default:
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR);
        }
        return operationType;
    }

    private String getReinsurers(List<CgnciReinsurerVO> reinsurers) {
        if (VerifyUtils.isEmpty(reinsurers)) {
            return null;
        }
        return reinsurers.stream().map(CgnciReinsurerVO::getReinsurerName).collect(Collectors.joining(","));
    }

    /**
     * 净自留份额=临分分出险种自留额汇总/直保保单保额汇总
     */


    private boolean containsAll(String riskSubTypeCode, String riskSubTypeCode1) {
        // 将字符串拆分为集合
        Set<String> set1 = new HashSet<>(Arrays.asList(riskSubTypeCode.split(",")));
        Set<String> set2 = new HashSet<>(Arrays.asList(riskSubTypeCode1.split(",")));

        // 检查 set1 是否完全包含 set2
        return set1.containsAll(set2);
    }

    private void validationByInsurance(CgnciBusinessInsuranceDO checkInsurance, CgnciBusinessInsuranceSaveOrUpdateDTO updateDTO) {
        // 保单止期不可早于保单起期
        if (updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().after(updateDTO.getBusinessInsuranceUpdateDTO().getEndDate())) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "保单止期不可早于保单起期", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "保单止期不可早于保单起期");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "保单止期不可早于保单起期");
        }

        // 必须上传查勘报告
        String isSurveyReport = updateDTO.getBusinessInsuranceUpdateDTO().getIsSurveyReport();
        if ("1".equals(isSurveyReport)) {
            if (VerifyUtils.isEmpty(updateDTO.getAccessoryDTOList())) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "必须上传查勘报告", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "当有无查勘报告选择为“有”时，文件清单中必须存在上传文件类型“查勘报告”的文件");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "必须上传查勘报告");
            }
            // 查询文件是否有查勘资料
            List<Long> accIds = updateDTO.getAccessoryDTOList().stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO::getAccId).collect(Collectors.toList());
            List<CgnciAccessoryDO> accessoryList = cgnciAccessoryService.listByIds(accIds);
            CgnciAccessoryDO accessory = accessoryList.stream().filter(acc -> "surveyReport".equals(acc.getAccType())).findFirst().orElse(null);
            if (VerifyUtils.isEmpty(accessory)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "必须上传查勘报告", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "当有无查勘报告选择为“有”时，文件清单中必须存在上传文件类型“查勘报告”的文件");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "必须上传查勘报告");
            }
        }


        // 校验单一险种分人的承接限额是否超该险种年度最大净自留限额,如果超出的话，需要校验单一险种临分分出的所有再保人分出限额汇总是否低于分人的承接限额-最大净自留限额，如果低于的话。提示：{险种名称-险种代码}临分分出限额超过该险种年度最大净自留限额
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciUnderwritingPolicyUpdateDTO> underwritingPolicyList = updateDTO.getUnderwritingPolicyDTO();
        if (VerifyUtils.isEmpty(underwritingPolicyList)) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "超净自留处理方式不能为空", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "超净自留处理方式不能为空");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "超净自留处理方式不能为空");
        }
        // 获取分人信息
        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO divideInDTO = updateDTO.getDivideInDTO();
        if (VerifyUtils.isEmpty(divideInDTO)) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "分入信息不能为空", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "分入信息不能为空");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "分入信息不能为空");
        }
        // 获取分人险种
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> risks = divideInDTO.getRisks();
        risks.forEach(risk -> {
            // 获取当前险种所有标的信息
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO> riskInsureds = risk.getRiskInsureds();
            // 获取当前险种所有标的的层信息
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO> riskLayers =
                    riskInsureds.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskInsuredUpdateDTO::getRiskLayers).flatMap(List::stream).collect(Collectors.toList());

            // 获取分入信息该险种的承接限额汇总
            BigDecimal shareLimit = BeanUtils.sumBigDecimalProperty(riskLayers, CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskLayerUpdateDTO::getShareLimit);

            // 获取该险种超净自留处理方式
            CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciUnderwritingPolicyUpdateDTO underwritingPolicy =
                    underwritingPolicyList.stream().filter(value -> risk.getRiskSubTypeCode().equals(value.getRiskSubTypeCode())).findFirst().orElse(null);
            if (VerifyUtils.isEmpty(underwritingPolicy)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "年度最大净自留限额险种-" + risk.getRiskSubType() + "为空", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "年度最大净自留限额险种不能为空");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "年度最大净自留限额险种-" + risk.getRiskSubType() + "为空");
            }
            if (VerifyUtils.isEmpty(underwritingPolicy.getRetentionRate())) {
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "请配置超净自留处理方式的汇率");
            }

            BigDecimal insuredAmount = "USD".equals(underwritingPolicy.getRetentionCurrency()) ? underwritingPolicy.getInsuredAmountDollar() : underwritingPolicy.getInsuredAmountRmb();
            insuredAmount = insuredAmount.multiply(underwritingPolicy.getRetentionRate());
            // 如果分人险种的承接限额大于年度该险种年度最大净自留限额
            if (shareLimit.compareTo(insuredAmount) > 0) {
                // 获取临分分出信息，如果为空，提示错误
                CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO lfDivideOutDTO = updateDTO.getLfDivideOutDTO();
                if (VerifyUtils.isEmpty(lfDivideOutDTO)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "单一险种承接限额超出最大净自留限额，需要为该险种设置临分分出限额");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                }

                // 获取所有再保人
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerUpdateDTO> reinsurers = lfDivideOutDTO.getReinsurers();
                if (VerifyUtils.isEmpty(reinsurers)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "单一险种承接限额超出最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                }

                // 获取所有再保人对应的险种
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskUpdateDTO> allReinsurersRisks
                        = reinsurers.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerUpdateDTO::getRisks).flatMap(List::stream).collect(Collectors.toList());
                if (VerifyUtils.isEmpty(allReinsurersRisks)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "单一险种承接限额超出最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                }

                // 获取该险种的临分分出再保人
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskUpdateDTO> reinsurersRisks
                        = allReinsurersRisks.stream().filter(value -> risk.getRiskSubTypeCode().equals(value.getRiskSubTypeCode())).collect(Collectors.toList());
                if (VerifyUtils.isEmpty(reinsurersRisks)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "单一险种承接限额超出最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                }

                // 获取该险种的临分分出的分出限额汇总
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskInsuredUpdateDTO> reinsurersRiskInsureds
                        = reinsurersRisks.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskUpdateDTO::getRiskInsureds).flatMap(List::stream).collect(Collectors.toList());
                if (VerifyUtils.isEmpty(reinsurersRiskInsureds)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "单一险种承接限额超出最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}承接限额超过该险种超净自留处理方式的最大净自留限额，需要为该险种设置临分分出-再保人分出限额");
                }


                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskLayerUpdateDTO> reinsurersRiskLayers
                        = reinsurersRiskInsureds.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskInsuredUpdateDTO::getRiskLayers).flatMap(List::stream).collect(Collectors.toList());
                BigDecimal cededLimit = BeanUtils.sumBigDecimalProperty(reinsurersRiskLayers, CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsurerRiskLayerUpdateDTO::getCededLimit);
                // 如果该险种的临分分出的分出限额汇总低于分人的承接限额-最大净自留限额，提示错误
                if (cededLimit.compareTo(shareLimit.subtract(insuredAmount)) < 0) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}再保人分出后的分出限额超过该险种超净自留处理方式的最大净自留限额", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "单一险种分出后的分出限额超过该险种超净自留处理方式的最大净自留限额\n" +
                            "注：仅考虑临分分出后自留额，合约分出暂不考虑");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{" + risk.getRiskSubType() + "-" + risk.getRiskSubTypeCode() + "}再保人分出后的分出限额超过该险种超净自留处理方式的最大净自留限额");
                }
            }
        });


        // 该业务倒签，请上传倒签资料
        /*if (checkInsurance.getCreateTime().after(DateUtils.getTimeByType(updateDTO.getBusinessInsuranceUpdateDTO().getStartDate(), "start"))) {
            if (VerifyUtils.isEmpty(updateDTO.getAccessoryDTOList())) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "该业务倒签，请上传倒签资料", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "保单倒签，在流转至总经理前未上传倒签资料");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该业务倒签，请上传倒签资料");
            }
            // 查询文件是否有倒签资料
            List<Long> accIds = updateDTO.getAccessoryDTOList().stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO::getAccId).collect(Collectors.toList());
            List<CgnciAccessoryDO> accessoryList = cgnciAccessoryService.listByIds(accIds);
            CgnciAccessoryDO accessory = accessoryList.stream().filter(acc -> "backInformation".equals(acc.getAccType())).findFirst().orElse(null);
            if (VerifyUtils.isEmpty(accessory)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "该业务倒签，请上传倒签资料", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "保单倒签，在流转至总经理前未上传倒签资料");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该业务倒签，请上传倒签资料");
            }
        }*/

        // 校验保单起保日期不在合约生效期间内
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> hyDivideOutDTOList = updateDTO.getHyDivideOutDTOList();
        if (VerifyUtils.isNotEmpty(hyDivideOutDTOList)) {
            // 查询合约的起止日期
            CgnciBusinessInsuranceDO hyInsurance = this.getOne(new LambdaQueryWrapper<CgnciBusinessInsuranceDO>().eq(CgnciBusinessInsuranceDO::getBusinessNo, hyDivideOutDTOList.get(0).getContractNo()).eq(CgnciBusinessInsuranceDO::getIsMirror, "0").eq(CgnciBusinessInsuranceDO::getStatus, "3"));
            if (updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().before(hyInsurance.getStartDate()) || updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().after(hyInsurance.getEndDate())) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "项目保单日期不在合约生效期间内", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "项目起保日期需在合约生效期间内");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "项目保单日期不在合约生效期间内");
            }

            // {险种XX}不在合约的险种范围内
            //String[] riskSubTypes = updateDTO.getBusinessProjectUpdateDTO().getRiskSubType().split(",");
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciUnderwritingPolicyUpdateDTO> underwritingPolicyDTO = updateDTO.getUnderwritingPolicyDTO();
            // 过滤掉分出安排是合约分出的list
            underwritingPolicyDTO = underwritingPolicyDTO.stream().filter(value -> value.getReinsuranceArrangement().contains("2")).collect(Collectors.toList());
            String[] riskSubTypes = underwritingPolicyDTO.stream()
                    .map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciUnderwritingPolicyUpdateDTO::getRiskSubType)
                    .collect(Collectors.joining(",")).split(",");
            for (String riskSubType : riskSubTypes) {
                AtomicBoolean flag = new AtomicBoolean(false);
                Map<String, List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO>> hyDivideOutMap = hyDivideOutDTOList.stream().collect(Collectors.groupingBy(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO::getContractNo));
                hyDivideOutMap.forEach((contractNo, hyDivideOutList) -> {
                    for (CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO hyDivideOut : hyDivideOutList) {
                        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> hyRisks = hyDivideOut.getRisks();
                        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO cgnciReinsuranceRiskUpdateDTO = hyRisks.stream().filter(vules -> riskSubType.equals(vules.getRiskSubType())).findFirst().orElse(null);
                        if (VerifyUtils.isNotEmpty(cgnciReinsuranceRiskUpdateDTO)) {
                            flag.set(true);
                            break;
                        }
                    }
                });
                if (!flag.get()) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{险种-" + riskSubType + "}不在合约的险种范围内", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "需要合约分出的险种不在合约的险种范围内");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{险种-" + riskSubType + "}不在合约的险种范围内");
                }
            }
        }
    }


    private void validationByDivideIn(CgnciBusinessInsuranceDO checkInsurance, CgnciBusinessInsuranceSaveOrUpdateDTO updateDTO) {
        // 合约名称重复，请修改
        CgnciBusinessInsuranceDO checkDivideOutName = this.getOne(new LambdaQueryWrapper<CgnciBusinessInsuranceDO>()
                .eq(CgnciBusinessInsuranceDO::getBusinessName, updateDTO.getBusinessInsuranceUpdateDTO().getBusinessName())
                .eq(CgnciBusinessInsuranceDO::getIsMirror, "0")
                .notIn(CgnciBusinessInsuranceDO::getFormNo, checkInsurance.getFormNo())
                .notIn(CgnciBusinessInsuranceDO::getStatus, Arrays.asList("0", "2", "4")));
        if (VerifyUtils.isNotEmpty(checkDivideOutName)) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约名称重复，请修改", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "合约名称不可重复");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约名称重复，请修改");
        }

        // 合约止期不可早于项目起期
        // 查询项目信息
        CgnciBusinessProjectDO businessProjectDO = cgnciBusinessProjectService.getById(updateDTO.getBusinessInsuranceUpdateDTO().getProjectId());
        if (updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().before(businessProjectDO.getStartDate())) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约止期不可早于项目起期", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "合约止期不可早于项目起期");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约止期不可早于项目起期");
        }

        // 合约止期不可早于合约起期
        if (updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().after(updateDTO.getBusinessInsuranceUpdateDTO().getEndDate())) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约止期不可早于合约起期", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "合约止期不可早于项目起期");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约止期不可早于合约起期");
        }

        // 必须上传查勘报告
        String isSurveyReport = updateDTO.getBusinessInsuranceUpdateDTO().getIsSurveyReport();
        if ("1".equals(isSurveyReport)) {
            if (VerifyUtils.isEmpty(updateDTO.getAccessoryDTOList())) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "必须上传查勘报告", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "当有无查勘报告选择为“有”时，文件清单中必须存在上传文件类型“查勘报告”的文件");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "必须上传查勘报告");
            }
            // 查询文件是否有查勘资料
            List<Long> accIds = updateDTO.getAccessoryDTOList().stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO::getAccId).collect(Collectors.toList());
            List<CgnciAccessoryDO> accessoryList = cgnciAccessoryService.listByIds(accIds);
            CgnciAccessoryDO accessory = accessoryList.stream().filter(acc -> "surveyReport".equals(acc.getAccType())).findFirst().orElse(null);
            if (VerifyUtils.isEmpty(accessory)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "必须上传查勘报告", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "当有无查勘报告选择为“有”时，文件清单中必须存在上传文件类型“查勘报告”的文件");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "必须上传查勘报告");
            }
        }

        // 该业务倒签，请上传倒签资料
        /*if (checkInsurance.getCreateTime().after(DateUtils.getTimeByType(updateDTO.getBusinessInsuranceUpdateDTO().getStartDate(), "start"))) {
            if (VerifyUtils.isEmpty(updateDTO.getAccessoryDTOList())) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "该业务倒签，请上传倒签资料", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "预约临分/合约分入倒签，在流转至总经理前未上传倒签资料");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该业务倒签，请上传倒签资料");
            }
            // 查询文件是否有倒签资料
            List<Long> accIds = updateDTO.getAccessoryDTOList().stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO::getAccId).collect(Collectors.toList());
            List<CgnciAccessoryDO> accessoryList = cgnciAccessoryService.listByIds(accIds);
            CgnciAccessoryDO accessory = accessoryList.stream().filter(acc -> "backInformation".equals(acc.getAccType())).findFirst().orElse(null);
            if (VerifyUtils.isEmpty(accessory)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "该业务倒签，请上传倒签资料", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "预约临分/合约分入倒签，在流转至总经理前未上传倒签资料");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该业务倒签，请上传倒签资料");
            }
        }*/

        // 校验合约分出
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> hyDivideOutDTOList = updateDTO.getHyDivideOutDTOList();
        if (VerifyUtils.isNotEmpty(hyDivideOutDTOList)) {
            // 分项信息险种汇总
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> risks = hyDivideOutDTOList.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO::getRisks).flatMap(List::stream).collect(Collectors.toList());
            if (VerifyUtils.isEmpty(risks)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "至少存在一条分项信息", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "至少存在一条分项信息");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "至少存在一条分项信息");
            }

            // 合约类型为成数溢额混合，请分别添加成数分项、溢额分项
            String businessSubform = updateDTO.getBusinessInsuranceUpdateDTO().getBusinessSubform();
            if ("3".equals(businessSubform)) {
                // 具体业务类型分组
                Map<String, List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO>> businessTypeMap = hyDivideOutDTOList.stream().collect(Collectors.groupingBy(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO::getBusinessType));
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> reinsuranceList1 = businessTypeMap.get("1");
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> reinsuranceList2 = businessTypeMap.get("2");
                if (VerifyUtils.isEmpty(reinsuranceList1) || VerifyUtils.isEmpty(reinsuranceList2)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约类型为成数溢额混合，请分别添加成数分项、溢额分项", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "当合约类型为成数溢额混合时，需至少分别存在一条分项类型为成数、溢额的分项信息");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约类型为成数溢额混合，请分别添加成数分项、溢额分项");
                }
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> reinsuranceRiskList1 = reinsuranceList1.get(0).getRisks();
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> reinsuranceRiskList2 = reinsuranceList2.get(0).getRisks();
                if (VerifyUtils.isEmpty(reinsuranceRiskList1) || VerifyUtils.isEmpty(reinsuranceRiskList2)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约类型为成数溢额混合，请分别添加成数分项、溢额分项", BusinessScenariosTypeEnum.POLICY_DIVIDEIN.getCode(), "当合约类型为成数溢额混合时，需至少分别存在一条分项类型为成数、溢额的分项信息");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约类型为成数溢额混合，请分别添加成数分项、溢额分项");
                }
            }

            // 校验分人起保日期不在合约生效期间内
            // 查询合约的起止日期
            CgnciBusinessInsuranceDO hyInsurance = this.getOne(new LambdaQueryWrapper<CgnciBusinessInsuranceDO>()
                    .eq(CgnciBusinessInsuranceDO::getBusinessNo, hyDivideOutDTOList.get(0).getContractNo())
                    .eq(CgnciBusinessInsuranceDO::getIsMirror, "0")
                    .eq(CgnciBusinessInsuranceDO::getStatus, "3"));
            if (updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().before(hyInsurance.getStartDate()) || updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().after(hyInsurance.getEndDate())) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "分人日期不在合约生效期间内", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "项目起保日期需在合约生效期间内");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "分人日期不在合约生效期间内");
            }

            // {险种XX}不在合约的险种范围内
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciUnderwritingPolicyUpdateDTO> underwritingPolicyDTO = updateDTO.getUnderwritingPolicyDTO();
            // 过滤掉分出安排是合约分出的list
            underwritingPolicyDTO = underwritingPolicyDTO.stream().filter(value -> value.getReinsuranceArrangement().contains("2")).collect(Collectors.toList());
            String[] riskSubTypes = underwritingPolicyDTO.stream()
                    .map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciUnderwritingPolicyUpdateDTO::getRiskSubType)
                    .collect(Collectors.joining(",")).split(",");
            for (String riskSubType : riskSubTypes) {
                AtomicBoolean flag = new AtomicBoolean(false);
                Map<String, List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO>> hyDivideOutMap = hyDivideOutDTOList.stream().collect(Collectors.groupingBy(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO::getContractNo));
                hyDivideOutMap.forEach((contractNo, hyDivideOutList) -> {
                    for (CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO hyDivideOut : hyDivideOutList) {
                        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> hyRisks = hyDivideOut.getRisks();
                        CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO cgnciReinsuranceRiskUpdateDTO = hyRisks.stream().filter(vules -> riskSubType.equals(vules.getRiskSubType())).findFirst().orElse(null);
                        if (VerifyUtils.isNotEmpty(cgnciReinsuranceRiskUpdateDTO)) {
                            flag.set(true);
                            break;
                        }
                    }
                });
                if (!flag.get()) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "{险种-" + riskSubType + "}不在合约的险种范围内", BusinessScenariosTypeEnum.POLICY_INSURANCE.getCode(), "需要合约分出的险种不在合约的险种范围内");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "{险种-" + riskSubType + "}不在合约的险种范围内");
                }
            }
        }

    }


    private void validationByDivideOut(CgnciBusinessInsuranceDO checkInsurance, CgnciBusinessInsuranceSaveOrUpdateDTO updateDTO) {
        // 合约名称重复，请修改
        CgnciBusinessInsuranceDO checkDivideOutName = this.getOne(new LambdaQueryWrapper<CgnciBusinessInsuranceDO>()
                .eq(CgnciBusinessInsuranceDO::getBusinessName, updateDTO.getBusinessInsuranceUpdateDTO().getBusinessName())
                .eq(CgnciBusinessInsuranceDO::getIsMirror, "0")
                .notIn(CgnciBusinessInsuranceDO::getFormNo, checkInsurance.getFormNo())
                .notIn(CgnciBusinessInsuranceDO::getStatus, Arrays.asList("0", "2", "4")));
        if (VerifyUtils.isNotEmpty(checkDivideOutName)) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约名称重复，请修改", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "合约名称不可重复");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约名称重复，请修改");
        }

        // 合约止期不可早于合约起期
        if (updateDTO.getBusinessInsuranceUpdateDTO().getStartDate().after(updateDTO.getBusinessInsuranceUpdateDTO().getEndDate())) {
            saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约止期不可早于合约起期", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "合约止期不可早于合约起期");
            throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约止期不可早于合约起期");
        }

        // 至少存在一条分项信息
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> hyDivideOutDTOList = updateDTO.getHyDivideOutDTOList();
        if (VerifyUtils.isNotEmpty(hyDivideOutDTOList)) {
            // 分项信息险种汇总
            List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> risks = hyDivideOutDTOList.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO::getRisks).flatMap(List::stream).collect(Collectors.toList());
            if (VerifyUtils.isEmpty(risks)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "至少存在一条分项信息", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "至少存在一条分项信息");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "至少存在一条分项信息");
            }

            // 合约类型为成数溢额混合，请分别添加成数分项、溢额分项
            String businessSubform = updateDTO.getBusinessInsuranceUpdateDTO().getBusinessSubform();
            if ("3".equals(businessSubform)) {
                // 具体业务类型分组
                Map<String, List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO>> businessTypeMap = hyDivideOutDTOList.stream().collect(Collectors.groupingBy(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO::getBusinessType));
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> reinsuranceList1 = businessTypeMap.get("1");
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceInfoInsuranceUpdateDTO> reinsuranceList2 = businessTypeMap.get("2");
                if (VerifyUtils.isEmpty(reinsuranceList1) || VerifyUtils.isEmpty(reinsuranceList2)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约类型为成数溢额混合，请分别添加成数分项、溢额分项", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "当合约类型为成数溢额混合时，需至少分别存在一条分项类型为成数、溢额的分项信息");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约类型为成数溢额混合，请分别添加成数分项、溢额分项");
                }
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> reinsuranceRiskList1 = reinsuranceList1.get(0).getRisks();
                List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciReinsuranceRiskUpdateDTO> reinsuranceRiskList2 = reinsuranceList2.get(0).getRisks();
                if (VerifyUtils.isEmpty(reinsuranceRiskList1) || VerifyUtils.isEmpty(reinsuranceRiskList2)) {
                    saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "合约类型为成数溢额混合，请分别添加成数分项、溢额分项", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "当合约类型为成数溢额混合时，需至少分别存在一条分项类型为成数、溢额的分项信息");
                    throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "合约类型为成数溢额混合，请分别添加成数分项、溢额分项");
                }
            }
        }

        // 该业务倒签，请上传倒签资料
        /*if (checkInsurance.getCreateTime().after(DateUtils.getTimeByType(updateDTO.getBusinessInsuranceUpdateDTO().getStartDate(), "start"))) {
            if (VerifyUtils.isEmpty(updateDTO.getAccessoryDTOList())) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "该业务倒签，请上传倒签资料", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "分出合约倒签，在流转至总经理前未上传倒签资料");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该业务倒签，请上传倒签资料");
            }
            // 查询文件是否有倒签资料
            List<Long> accIds = updateDTO.getAccessoryDTOList().stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.AccessoryDTO::getAccId).collect(Collectors.toList());
            List<CgnciAccessoryDO> accessoryList = cgnciAccessoryService.listByIds(accIds);
            CgnciAccessoryDO accessory = accessoryList.stream().filter(acc -> "backInformation".equals(acc.getAccType())).findFirst().orElse(null);
            if (VerifyUtils.isEmpty(accessory)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "该业务倒签，请上传倒签资料", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "分出合约倒签，在流转至总经理前未上传倒签资料");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "该业务倒签，请上传倒签资料");
            }
        }*/

        // 币种相关
        List<CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciExchangeRateUpdateDTO> exchangeRateDTOList = updateDTO.getExchangeRateDTOList();
        if (VerifyUtils.isNotEmpty(exchangeRateDTOList)) {
            CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciExchangeRateUpdateDTO exchangeRate = exchangeRateDTOList.stream().filter(value -> "CNY".equals(value.getCurrency())).findFirst().orElse(null);
            if (VerifyUtils.isNotEmpty(exchangeRate)) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "币种信息-此次为外币转人民币兑换汇率，请选择其他币种", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "次为外币转人民币兑换汇率，请选择其他币种");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "币种信息-此次为外币转人民币兑换汇率，请选择其他币种");
            }
            boolean hasDuplicate = exchangeRateDTOList.stream().map(CgnciBusinessInsuranceSaveOrUpdateDTO.CgnciExchangeRateUpdateDTO::getCurrency) // 提取 currency 属性
                    .distinct() // 去重
                    .count() != exchangeRateDTOList.size(); // 比较大小
            if (hasDuplicate) {
                saveErrorMessage(String.valueOf(checkInsurance.getInsuranceId()), "币种信息-币种重复", BusinessScenariosTypeEnum.POLICY_DIVIDEOUT.getCode(), "币种不可重复");
                throw new GlobalException(ResponseCodeEnum.HTTP_REQUEST_SERVICE_ERROR, "币种信息-币种重复");
            }
        }

    }


    @Autowired
    private CgnciClaimAlertInfoService cgnciClaimAlertInfoService;

    private void saveErrorMessage(String taskNo, String content, String businessSceneType, String ruleName) {
        CgnciClaimAlertInfoDO info = new CgnciClaimAlertInfoDO();
        info.setContent(content);
        info.setRuleName(ruleName);
        info.setBusinessNo(taskNo);
        info.setAlertType(AlertInfoTypeEnum.ERROR.getCode());
        info.setBusinessScene(BusinessScenariosEnum.POLICY.getCode());
        info.setBusinessSceneType(businessSceneType);
        cgnciClaimAlertInfoService.clearHistoryAndSave(info);

    }

    private void saveErrorMessage(String taskNo, String content, String businessSceneType, String ruleName, String alertType) {
        CgnciClaimAlertInfoDO info = new CgnciClaimAlertInfoDO();
        info.setContent(content);
        info.setRuleName(ruleName);
        info.setBusinessNo(taskNo);
        info.setAlertType(alertType);
        info.setBusinessScene(BusinessScenariosEnum.POLICY.getCode());
        info.setBusinessSceneType(businessSceneType);
        cgnciClaimAlertInfoService.clearHistoryAndSave(info);

    }

}
